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

  

posted @ 2018-12-14 11:17  赵客缦胡缨-Nicholas  阅读(2177)  评论(0编辑  收藏  举报