middleware.go
1.49 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
package webutility
import (
"net/http"
"time"
"git.to-net.rs/marko.tikvic/gologger"
)
func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
SetDefaultHeaders(w)
if req.Method == http.MethodOptions {
return
}
h(w, req)
}
}
func ParseForm(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
err := req.ParseForm()
if err != nil {
BadRequest(w, req, err.Error())
return
}
h(w, req)
}
}
func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
err := req.ParseMultipartForm(32 << 20)
if err != nil {
BadRequest(w, req, err.Error())
return
}
h(w, req)
}
}
var trafficLogger *gologger.Logger
func EnableLogging(log string) error {
var err error
trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
return err
}
func Log(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
t1 := time.Now()
in := trafficLogger.RequestLog(req, "")
wRec := WrapWithStatusRecorder(w)
h(wRec, req)
t2 := time.Now()
out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0)
trafficLogger.LogHTTPTraffic(in, out)
}
}
func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if _, err := AuthCheck(req, roles); err != nil {
Unauthorized(w, req, err.Error())
return
}
h(w, req)
}
}