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

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

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


呼如林
浏览 214回答 4
4回答

小怪兽爱吃肉

这种方法是可行的。&nbsp; &nbsp; type loggingResponseWriter struct {&nbsp; &nbsp; &nbsp; &nbsp; http.ResponseWriter&nbsp; &nbsp; &nbsp; &nbsp; statusCode int&nbsp; &nbsp; }&nbsp; &nbsp; func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {&nbsp; &nbsp; &nbsp; &nbsp; return &loggingResponseWriter{w, http.StatusOK}&nbsp; &nbsp; }&nbsp; &nbsp; func (lrw *loggingResponseWriter) WriteHeader(code int) {&nbsp; &nbsp; &nbsp; &nbsp; lrw.statusCode = code&nbsp; &nbsp; &nbsp; &nbsp; lrw.ResponseWriter.WriteHeader(code)&nbsp; &nbsp; }&nbsp; &nbsp; func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler {&nbsp; &nbsp; &nbsp; &nbsp; return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("--> %s %s", req.Method, req.URL.Path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lrw := NewLoggingResponseWriter(w)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wrappedHandler.ServeHTTP(lrw, req)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; statusCode := lrw.statusCode&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("<-- %d %s", statusCode, http.StatusText(statusCode))&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }

泛舟湖上清波郎朗

使用内格罗尼。它的工作原理与@huangapple 的答案相同,但处理程序实际上实现了所有接口。import (&nbsp; &nbsp; "github.com/urfave/negroni")func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler {&nbsp; &nbsp; return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("--> %s %s", req.Method, req.URL.Path)&nbsp; &nbsp; &nbsp; &nbsp; lrw := negroni.NewResponseWriter(w)&nbsp; &nbsp; &nbsp; &nbsp; wrappedHandler.ServeHTTP(lrw, req)&nbsp; &nbsp; &nbsp; &nbsp; statusCode := lrw.Status()&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("<-- %d %s", statusCode, http.StatusText(statusCode))&nbsp; &nbsp; })}

慕桂英546537

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

精慕HU

在我的例子中,我不使用外部库,我不想包装http.ResponseWriter. 我必须在请求的上下文中添加响应的状态,以便以后在日志记录中使用。所以我创建了一个小帮手来同时在 ResponseWriter 和请求的上下文中写入状态。type AppContext stringvar StatusCode = AppContext("statuCode")func WriteHeaderAndContext(w http.ResponseWriter, statusCode int, r *http.Request) {&nbsp; &nbsp; ctx := context.WithValue(r.Context(), StatusCode, statusCode)&nbsp; &nbsp; *r = *(r.WithContext(ctx))&nbsp; &nbsp; w.WriteHeader(statusCode)}在日志记录中,我将值检索为r.Context().Value(StatusCode)缺点发生在被叫方,看起来有点不寻常。例如WriteHeaderAndContext(w, http.StatusCreated, r)我们通常做的地方w.WriteHeader(http.StatusCreated)
打开App,查看更多内容
随时随地看视频慕课网APP