diff options
Diffstat (limited to 'pkg/ext/log.go')
-rw-r--r-- | pkg/ext/log.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/pkg/ext/log.go b/pkg/ext/log.go new file mode 100644 index 0000000..a9d26a9 --- /dev/null +++ b/pkg/ext/log.go @@ -0,0 +1,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), + ) + } +} |