-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
81 lines (67 loc) · 2.18 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package gotk
import (
"context"
"net/http"
)
type HttpContext struct {
key string
*http.Request
}
func NewHttpContext(key string, r *http.Request) *HttpContext {
ctx := context.WithValue(r.Context(), key, make(map[string]any, 0))
*r = *(r.WithContext(ctx))
return &HttpContext{key: key, Request: r}
}
func (ctx *HttpContext) Set(key string, value any) bool {
data, _ := ctx.Request.Context().Value(key).(map[string]any)
_, ok := data[key]
data[key] = value
return ok
}
func (ctx *HttpContext) GetValue(key string) (any, bool) {
data, _ := ctx.Request.Context().Value(ctx.key).(map[string]any)
value, ok := data[key]
return value, ok
}
func (ctx *HttpContext) GetData() map[string]any {
data, _ := ctx.Request.Context().Value(ctx.key).(map[string]any)
return data
}
func MiddlewareHandler(origin string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Content-Type, Authorization, X-CSRF-Token
w.Header().Set(
"Access-Control-Expose-Headers",
"Access-Control-Allow-Origin, Access-Control-Allow-Headers, "+
"Content-Type, Content-Length",
)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, HEAD")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func MiddlewareFunc(origin string, hf http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Content-Type, Authorization, X-CSRF-Token
w.Header().Set(
"Access-Control-Expose-Headers",
"Access-Control-Allow-Origin, Access-Control-Allow-Headers, "+
"Content-Type, Content-Length",
)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, HEAD")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
hf(w, r)
}
}