How do I get Response statusCode in golang middleware?
ResponseWriter have only WriteHeader interface, I can't find get interface.
This method is feasible.
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{w, http.StatusOK}
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.Printf("--> %s %s", req.Method, req.URL.Path)
lrw := NewLoggingResponseWriter(w)
wrappedHandler.ServeHTTP(lrw, req)
statusCode := lrw.statusCode
log.Printf("<-- %d %s", statusCode, http.StatusText(statusCode))
})
}
Use negroni. It works the same as @huangapple answer, but with the handler actually implementing all the interfaces.
import (
"github.com/urfave/negroni"
)
func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.Printf("--> %s %s", req.Method, req.URL.Path)
lrw := negroni.NewResponseWriter(w)
wrappedHandler.ServeHTTP(lrw, req)
statusCode := lrw.Status()
log.Printf("<-- %d %s", statusCode, http.StatusText(statusCode))
})
}
Long story short, you should wrap http.ResponseWriter by yourself or using libraries. If you want to implement it by yourself you can find some hints from Negroni source code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With