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

  

相关文章:

  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2021-12-19
相关资源
相似解决方案