如何检查ResponseWriter是否已经写入

How to check if ResponseWriter has been written

使用Golang的net/http包,如何查看ResponseWriter是否已经写入?我收到以下错误消息:

http: multiple response.WriteHeader calls

当然我可以 return 布尔值等从我的函数中指示天气我用重定向或其他东西写到 ResponseWriter,我试过了,但我肯定能够检查是否ResponseWriter之前写过,我用一个简单的方法写过

我正在寻找一个看起来像下面这样的函数,我可以在写入 ResponseWriter:

之前使用它
if w.Header().Get("Status-Code") == "" {
    http.Redirect(w, r, "/", http.StatusSeeOther)
} else {
    fmt.Println("Response Writer has already been written to.")
}

上面的代码似乎不起作用...有人知道如何检查 ResponseWriter 是否已写入吗?

唯一的方法是使用 http.ResponseWriter:

的自定义实现
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
    }
}

我也拼了a simple package帮我处理了这件事。喜欢的也可以随意使用。