samber / slog-chi

🚨 Chi middleware for slog logger
https://pkg.go.dev/github.com/samber/slog-chi
MIT License
44 stars 6 forks source link

Use status code from the wrapped response writer instead of request #4

Closed brnck closed 11 months ago

brnck commented 11 months ago

There is an issue with Filters that use status code to include/exclude log.

r.Response is nil, therefore:

2023/10/25 21:14:47 http: panic serving 127.0.0.1:45324: runtime error: invalid memory address or nil pointer dereference
goroutine 6 [running]:
net/http.(*conn).serve.func1()
    /usr/local/go/src/net/http/server.go:1868 +0xb9
panic({0x6d0b40?, 0x96bd50?})
    /usr/local/go/src/runtime/panic.go:920 +0x270
main.main.AcceptStatusGreaterThanOrEqual.func7({0x720193?, 0x6bd7e0?}, 0x79f6f0?)
    /home/abe/Projects/slog-chi/filters.go:85 +0xb
main.main.NewWithFilters.NewWithConfig.func11.1.1()
    /home/abe/Projects/slog-chi/middleware.go:184 +0x16f6
main.main.NewWithFilters.NewWithConfig.func11.1({0x7a2b20, 0xc000104000}, 0xc000100100)
    /home/abe/Projects/slog-chi/middleware.go:200 +0x390
net/http.HandlerFunc.ServeHTTP(0x7a3308?, {0x7a2b20?, 0xc000104000?}, 0x96b670?)
    /usr/local/go/src/net/http/server.go:2136 +0x29
github.com/go-chi/chi/v5.(*Mux).ServeHTTP(0xc0000881e0, {0x7a2b20, 0xc000104000}, 0xc000100000)
    /home/abe/go/pkg/mod/github.com/go-chi/chi/v5@v5.0.10/mux.go:90 +0x315
net/http.serverHandler.ServeHTTP({0xc00009d200?}, {0x7a2b20?, 0xc000104000?}, 0x6?)
    /usr/local/go/src/net/http/server.go:2938 +0x8e
net/http.(*conn).serve(0xc0000ba510, {0x7a32d0, 0xc00009d110})
    /usr/local/go/src/net/http/server.go:2009 +0x5f4
created by net/http.(*Server).Serve in goroutine 1
    /usr/local/go/src/net/http/server.go:3086 +0x5cb

This PR fixes that by using middleware.WrapResponseWriter to get status code instead of http.Request

Test case:

Using example app in example directory initialize middleware with filters

r.Use(slogchi.NewWithFilters(logger.WithGroup("http"), slogchi.AcceptStatusGreaterThanOrEqual(http.StatusOK)))

instead of

r.Use(slogchi.New(logger.WithGroup("http")))

Run the app and execute:

curl localhost:4242
curl: (52) Empty reply from server

Check the app logs, you will see the same as I've described at the beginning of this description. Now apply PR changes and repeat the process:

curl localhost:4242
welcome%                         

Logs are, also, there:

go run example.go
time=2023-10-25T21:30:05.412+03:00 level=INFO msg=OK env=production http.time=2023-10-25T18:30:05Z http.latency=27.569µs http.method=GET http.path=/ http.route="" http.status=200 http.user-agent=curl/7.81.0
samber commented 11 months ago

Oh!

Thanks.