-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
58 lines (50 loc) · 1.3 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
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"log"
"net/http"
"runtime/debug"
"time"
)
type ResponseWrapper struct {
http.ResponseWriter
Status int
}
func (wrap *ResponseWrapper) WriteHeader(status int) {
wrap.ResponseWriter.WriteHeader(status)
wrap.Status = status
}
type Middleware func(http.Handler) http.Handler
func LoggingMiddleware(logger *log.Logger) Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
logger.Println(
"err", err,
"trace", string(debug.Stack()),
)
}
}()
wrapper := &ResponseWrapper{
ResponseWriter: w,
}
start := time.Now()
next.ServeHTTP(wrapper, r)
logger.Println(r.Method, r.URL.EscapedPath(), "status", wrapper.Status, "response time", time.Since(start))
}
return http.HandlerFunc(fn)
}
}
type ErrorHandler func(http.ResponseWriter, *http.Request) error
func (logicFunc ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := logicFunc(w, r)
if err != nil {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(http.StatusInternalServerError)
resp := []byte(fmt.Sprintf(`{"error": %q}`, err.Error()))
w.Write(resp)
return
}
}