/
http-middleware.go
48 lines (40 loc) · 1.06 KB
/
http-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
46
47
48
package ditt
import (
"log"
"net/http"
"time"
)
type statusCatcher struct {
status int
http.ResponseWriter
}
func (catcher *statusCatcher) WriteHeader(statusCode int) {
catcher.status = statusCode
catcher.ResponseWriter.WriteHeader(statusCode)
}
func loggerHttpMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
c := &statusCatcher{
status: 0,
ResponseWriter: w,
}
next.ServeHTTP(c, r)
duration := time.Since(start)
log.Printf("%s %s %s %s\n", r.Method, r.RequestURI, http.StatusText(c.status), duration)
})
}
const (
sessionName = "auth-session"
sessionLoggedUserKey = "logged-user"
)
func sessionHttpMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := Env.CookiesStore.Get(r, sessionName)
value, exists := session.Values[sessionLoggedUserKey]
if exists {
r = r.WithContext(ContextWithLoggedUser(r.Context(), value.(string)))
}
next.ServeHTTP(w, r)
})
}