dsb238100 2015-08-08 18:53
浏览 111
已采纳

我如何知道net / http的ResponseWriter.Write()是否已被调用?

Suppose I have a chain of net/http Handlers, and an early one responds with an HTTP error (http.StatusInternalServerError, for instance). How can I detect this in the following handlers, and avoid sending additional data to the client?

Or is this entirely the wrong approach to the problem?

  • 写回答

2条回答 默认 最新

  • doushe8577 2015-08-08 19:47
    关注

    http.ResponseWriter is an interface. So just compose a new instance of it:

    type MyResponseWriter struct {
        http.ResponseWriter
        WroteHeader bool
    }
    
    func (w *MyResponseWriter) Write(b []byte) (int, error) {
        w.WroteHeader = true
        return w.ResponseWriter.Write(b)
    }
    
    func (w *MyResponseWriter) WriteHeader(code int) {
        w.WroteHeader = true
        w.ResponseWriter.WriteHeader(code)
    }
    

    And in your handlers:

    //...
    if w, ok := w.(*MyResponseWriter); ok && w.WroteHeader {
        log.Println("Already wrote, skipping")
        return
    }
    

    EDIT: Another thing to consider. Most of the time if you have a "chain" of handlers that means that a handler is called inside a handler. So if you have something like

    type Handler1 struct { http.Handler }
    type Handler2 struct { http.Handler }
    type Handler3 struct { http.Handler }
    var MyHandler http.Handler = Handler1{Handler2{Handler3{h}}}
    

    as long as each of those call the inner handler as the last thing they do with w and r, you should be fine because then w and r won't even reach the inner handler. E.g.

    func (h Handler2) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        if somethingBadHappened() {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
        h.ServeHTTP(w, r) // Not called if somethingBadHappened().
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看