middleware.go
1.87 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package middleware
import (
"net/http"
"time"
"git.to-net.rs/marko.tikvic/gologger"
web "git.to-net.rs/marko.tikvic/webutility"
)
var httpLogger *gologger.Logger
func SetAccessControlHeaders(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
web.SetAccessControlHeaders(w)
h(w, req)
}
}
// IgnoreOptionsRequests ...
func IgnoreOptionsRequests(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodOptions {
return
}
h(w, req)
}
}
// ParseForm ...
func ParseForm(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
err := req.ParseForm()
if err != nil {
web.BadRequest(w, req, err.Error())
return
}
h(w, req)
}
}
// ParseMultipartForm ...
func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
err := req.ParseMultipartForm(32 << 20)
if err != nil {
web.BadRequest(w, req, err.Error())
return
}
h(w, req)
}
}
// SetLogger ...
func SetLogger(logger *gologger.Logger) {
httpLogger = logger
}
// LogHTTP ...
func LogHTTP(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if httpLogger == nil {
h(w, req)
return
}
t1 := time.Now()
claims, _ := web.GetTokenClaims(req)
in := httpLogger.LogHTTPRequest(req, claims.Username)
rec := web.NewStatusRecorder(w)
h(rec, req)
t2 := time.Now()
out := httpLogger.LogHTTPResponse(rec.Status(), t2.Sub(t1), rec.Size())
httpLogger.CombineHTTPLogs(in, out)
}
}
// Auth ...
func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if _, err := web.AuthCheck(req, roles); err != nil {
web.Unauthorized(w, req, err.Error())
return
}
h(w, req)
}
}