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
|
package server
import (
"net/http"
"website/internal/log"
)
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
// avoids warning: superfluous response.WriteHeader call
if lrw.statusCode != http.StatusOK {
lrw.ResponseWriter.WriteHeader(code)
}
}
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{w, http.StatusOK}
}
type wrappedHandlerOptions struct {
defaultHostname string
}
func wrapHandlerWithLogging(wrappedHandler http.Handler, opts wrappedHandlerOptions) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
scheme := r.Header.Get("X-Forwarded-Proto")
if scheme == "" {
scheme = "http"
}
host := r.Host
if host == "" {
host = opts.defaultHostname
}
lw := NewLoggingResponseWriter(w)
wrappedHandler.ServeHTTP(lw, r)
statusCode := lw.statusCode
log.Info(
"http request",
"scheme", scheme,
"method", r.Method,
"status", statusCode,
"host", host,
"path", r.URL.Path,
"location", lw.Header().Get("Location"),
)
})
}
|