From 6079b1d963f34ada5c4b25363f2319901e283936 Mon Sep 17 00:00:00 2001 From: "Gabriel A. Giovanini" Date: Sat, 8 Jun 2024 00:01:44 +0200 Subject: feat: Add error handling --- pkg/ext/log.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 pkg/ext/log.go (limited to 'pkg/ext/log.go') 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), + ) + } +} -- cgit v1.2.3