如何在golang中间件中获取Response statusCode?

时间:2018-11-13 01:39:15

标签: go

我如何在golang中间件中获取Response statusCode?

ResponseWriter只有WriteHeader接口,找不到get接口。

3 个答案:

答案 0 :(得分:0)

这种方法是可行的。

    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))
        })
    }

答案 1 :(得分:0)

长话短说,您应该自己包装或使用库包装http.ResponseWriter。如果您想自己实现它,可以从Negroni源代码中找到一些提示

答案 2 :(得分:0)

使用negroni。它的工作方式与@huangapple答案相同,但处理程序实际上实现了所有接口。

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))
    })
}