bahlo/goat

Middleware logging response status code

robintemme opened this issue · 2 comments

Maybe it's just me, but I'm struggling with writing a middleware that is logging the http status code of the response that goat sent.

Do you have any ideas how this can be accomplished?

I found a solution, was not that easy. I had to wrap http.ResponseWriter in order to be able to do this:

// loggingResponseWriter is a wrapper around http.ResponseWriter, also holding a status code
type loggingResponseWriter struct {
    status int
    http.ResponseWriter
}

// newLoggingResponseWriter initializes our loggingResponseWriter, defaulting to code 200
func newLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
    return &loggingResponseWriter{200, w}
}

// Status returns the status code of the loggingResponseWriter
func (w loggingResponseWriter) Status() int {
    return w.status
}

// WriteHeader writes the header and sets the status code
func (w *loggingResponseWriter) WriteHeader(code int) {
    w.status = code
    w.ResponseWriter.WriteHeader(code)
}

// AnswerLogger is a middleware that logs all answers with status code
func AnswerLogger(h http.Handler) http.Handler {
    return http.HandlerFunc(func(
        w http.ResponseWriter,
        r *http.Request,
    ) {
        l := newLoggingResponseWriter(w)
        h.ServeHTTP(l, r)
        log.Printf("%s %s - %3d", r.Method, r.URL.Path, l.Status())
    })
}

Sorry I bothered you with this. Still learning ¯\_(ツ)_/¯

bahlo commented

Nice 👌