Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Response statusCode in golang middleware?

Tags:

go

How do I get Response statusCode in golang middleware?

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

like image 881
huangapple Avatar asked Nov 13 '18 01:11

huangapple


3 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))
        })
    }
like image 130
huangapple Avatar answered Nov 09 '22 04:11

huangapple


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))
    })
}
like image 42
Karel Bílek Avatar answered Nov 09 '22 02:11

Karel Bílek


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

like image 45
Oleg Avatar answered Nov 09 '22 02:11

Oleg