How do I get Response statusCode in golang middleware?

Viewed 9511

How do I get Response statusCode in golang middleware?

ResponseWriter have only WriteHeader interface, I can't find get interface.

4 Answers

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

Related