码迷,mamicode.com
首页 > 其他好文 > 详细

golang 获取statuscode

时间:2018-12-14 13:11:01      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:turn   else   one   日志   middle   Golan   状态码   原因   ever   

 最近日志打印的时候需要打印状态码,但是因为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
    }
}

  

golang 获取statuscode

标签:turn   else   one   日志   middle   Golan   状态码   原因   ever   

原文地址:https://www.cnblogs.com/zhangym/p/10118366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!