blob: a9d26a9afd92ce2309d6f27653577a97a9b76c1e (
plain)
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
|
package ext
import (
"log/slog"
"net/http"
"time"
)
type statusWraper struct {
statusCode int
innerWriter http.ResponseWriter
}
func (s *statusWraper) Header() http.Header {
return s.innerWriter.Header()
}
func (s *statusWraper) Write(b []byte) (int, error) {
return s.innerWriter.Write(b)
}
func (s *statusWraper) WriteHeader(statusCode int) {
s.statusCode = statusCode
s.innerWriter.WriteHeader(statusCode)
}
func (s *statusWraper) StatusCode() int {
if s.statusCode == 0 {
return 200
}
return s.statusCode
}
func wrap(w http.ResponseWriter) *statusWraper {
return &statusWraper{
innerWriter: w,
}
}
func Log(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
s := wrap(w)
next(s, r)
slog.Info(
"Http request",
"method", r.Method,
"code", s.StatusCode(),
"path", r.URL,
"elapsed", time.Since(t),
)
}
}
|