-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddlewares.go
50 lines (41 loc) · 1021 Bytes
/
middlewares.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
package gohttplib
import (
"log"
"net/http"
"time"
)
type Middleware func(http.Handler) http.Handler
func AccessMiddlewareFactory(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Secret") != secret {
DefaultHTTP403().Write(w)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func RecoverMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("HTTP 500 %v", err)
HTTP500(err).Write(w)
return
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func LoggingMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
}
return http.HandlerFunc(fn)
}