-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
49 lines (44 loc) · 1.05 KB
/
Copy pathlogger.go
File metadata and controls
49 lines (44 loc) · 1.05 KB
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
package main
import (
"fmt"
"log/slog"
"net"
"net/http"
"time"
)
type statusRecorder struct {
http.ResponseWriter
status int
}
// WriteHeader overrides std WriteHeader to save response code.
func (rec *statusRecorder) WriteHeader(code int) {
rec.status = code
rec.ResponseWriter.WriteHeader(code)
}
// Logger is a logging middleware that logs useragent, RemoteAddr, Method, Host, Path and response.Status to stdlib log.
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
rec := statusRecorder{w, http.StatusOK}
next.ServeHTTP(&rec, r)
// remote := strings.Split(r.RemoteAddr, ":")[0]
remote, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
remote = r.RemoteAddr
}
if r.Header.Get("X-Forwarded-For") != "" {
remote = r.Header.Get("X-Forwarded-For")
}
details := fmt.Sprintf(
"%s %s%s %d %s %s %s",
r.Method,
r.Host,
r.URL.Path,
rec.status,
remote,
time.Since(now).String(),
r.UserAgent(),
)
slog.Info(details)
})
}