/
middleware.go
63 lines (51 loc) · 1.45 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
59
60
61
62
63
package middleware
import (
"net/http"
"time"
"go.uber.org/zap"
)
type HeaderParam = string
const (
ContentLength HeaderParam = "Content-Length"
UserAgent HeaderParam = "User-Agent"
Host HeaderParam = "Host"
ContentType HeaderParam = "Content-Type"
)
// InjectedLogging uses logging middleware
func InjectedLogging(logger *zap.Logger) func(http.Handler) http.Handler {
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.Error("Failure occurred during request processing")
}
}()
userAgent := r.Header.Get(UserAgent)
if len(userAgent) == 0 {
userAgent = "-"
}
contentLength := r.Header.Get(ContentLength)
if len(contentLength) == 0 {
contentLength = "-"
}
host := r.Header.Get(Host)
if host == "" {
host = r.RemoteAddr
}
contentType := r.Header.Get(ContentType)
if contentType == "" {
contentType = "-"
}
start := time.Now()
next.ServeHTTP(w, r)
logger.Info("HTTP request received",
zap.String("method", r.Method), zap.String("path", r.URL.EscapedPath()),
zap.Duration("duration", time.Since(start)), zap.String("content_type", contentType),
zap.String("content_length", contentLength),
zap.String("user_agent", userAgent), zap.String("host", host),
)
}
return http.HandlerFunc(fn)
}
}