diff options
author | Gabriel A. Giovanini <mail@gabrielgio.me> | 2024-06-08 00:01:44 +0200 |
---|---|---|
committer | Gabriel A. Giovanini <mail@gabrielgio.me> | 2024-06-08 00:01:44 +0200 |
commit | 6079b1d963f34ada5c4b25363f2319901e283936 (patch) | |
tree | f7f93616eb3dacfcebee486fe7542ec3adfb3950 /pkg/ext/log.go | |
parent | e9098e00fb6339b759df5b0df2e086cef8a7ce83 (diff) | |
download | cerrado-6079b1d963f34ada5c4b25363f2319901e283936.tar.gz cerrado-6079b1d963f34ada5c4b25363f2319901e283936.tar.bz2 cerrado-6079b1d963f34ada5c4b25363f2319901e283936.zip |
feat: Add error handling
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), + ) + } +} |