internalhttp.*MiddlewareLogger.loggingMiddleware   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 15
dl 0
loc 18
c 0
b 0
f 0
rs 9.65
nop 1
1
package internalhttp
2
3
import (
4
	"net/http"
5
	"time"
6
)
7
8
type statusWriter struct {
9
	http.ResponseWriter
10
	status int
11
}
12
13
func (w *statusWriter) WriteHeader(status int) {
14
	w.status = status
15
	w.ResponseWriter.WriteHeader(status)
16
}
17
18
type MiddlewareLogger struct{}
19
20
func NewMiddlewareLogger() *MiddlewareLogger {
21
	return &MiddlewareLogger{}
22
}
23
24
func (a *MiddlewareLogger) loggingMiddleware(next http.Handler) http.Handler {
25
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
26
		sw := &statusWriter{ResponseWriter: w}
27
28
		l := r.Context().Value(KeyLoggerID).(Logger)
29
		start := time.Now()
30
31
		next.ServeHTTP(sw, r)
32
33
		l.Debugf("%s [%s] %s %s %s %d %s %s %s\n",
34
			r.RemoteAddr,
35
			start.Format("02/Jan/2006:15:04:05 -0700"),
36
			r.Method,
37
			r.RequestURI,
38
			sw.status,
39
			http.StatusText(sw.status),
40
			time.Since(start).String(),
41
			r.Header.Get("User-Agent"),
42
		)
43
	})
44
}
45
46
func (a *MiddlewareLogger) setCommonHeadersMiddleware(next http.Handler) http.Handler {
47
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
48
		w.Header().Set("Content-Type", "application/json")
49
		next.ServeHTTP(w, r)
50
	})
51
}
52