gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:32:44 25 4
gpt4 key购买 nike

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

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

最佳答案

这个方法是可行的。

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

关于go - 如何在golang中间件中获取Response statusCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53272536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com