golang 获取statuscode
Posted zhangym
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 获取statuscode相关的知识,希望对你有一定的参考价值。
最近日志打印的时候需要打印状态码,但是因为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的主要内容,如果未能解决你的问题,请参考以下文章
golang goroutine例子[golang并发代码片段]