golang 获取statuscode

 最近日志打印的时候须要打印状态码,可是由于interface的缘由直接获取失败,http.Request里面的response不知道怎么使用,因此就本身重写writeheader,write来截取status日志

type doneWriter struct {
    http.ResponseWriter
    done bool   status int
}

func (w *doneWriter) WriteHeader(status int) {
    w.done = true   w.status= status
    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
    }
}
相关文章
相关标签/搜索