-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
45 lines (36 loc) · 1.04 KB
/
middleware.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
package main
import (
"net/http"
"github.com/sirupsen/logrus"
)
func NewLoggerMiddleware(logger *logrus.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.WithFields(logrus.Fields{
"remote_ip": r.RemoteAddr,
"url": r.URL.String(),
"headers": r.Header,
}).Info("received request")
next.ServeHTTP(w, r)
})
}
}
func NewJWTMiddleware(validator JWTRequestValidator) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := validator.ValidateRequest(r)
if err != nil {
logger.WithFields(logrus.Fields{
"remote_ip": r.RemoteAddr,
"url": r.URL.String(),
"error": err,
"token": token,
}).Warning("token is not valid")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
} else {
next.ServeHTTP(w, r)
}
})
}
}