最近日志打印的时候需要打印状态码,但是因为interface的原因直接获取失败,http.Request里面的response不知道怎么使用,所以就自己重写writeheader,write来截取status
type doneWriter struct { http.ResponseWriter done bool } func (w *doneWriter) WriteHeader(status int) { w.done = true w.ResponseWriter.WriteHeader(status) } func (w *doneWriter) Write(b []byte) (int, error) { w.done = true return w.ResponseWriter.Write(b) } func myMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { dw := &doneWriter{ResponseWriter: w} next.ServeHTTP(dw, r) if dw.done { // Something already wrote a response return } // Nothing else wrote a response w.WriteHeader(http.StatusOK) // Whatever you want here } }
原文地址:https://www.cnblogs.com/zhangym/p/10118366.html
时间: 2024-11-06 07:11:04