如何检查ResponseWriter是否已编写 [英] How to check if ResponseWriter has been written
问题描述
使用Golang的 net/http 程序包,如何检查ResponseWriter
是否具有被写到?我收到以下错误消息:
Using Golang's net/http package, how can I check if the ResponseWriter
has been written to? I am receiving the following error message:
http:多个响应.WriteHeader调用
http: multiple response.WriteHeader calls
当然,我可以从函数中返回布尔值等,以表明我使用重定向或其他方式写到ResponseWriter
的天气,这是我尝试过的,但是可以肯定的是,我能够检查以前是否已写入ResponseWriter
我用一种简单的方法来写它.
Of course I can return booleans and such from my functions indicating weather I wrote to the ResponseWriter
with a redirect or something, which I tried, but surely I am able to check if the ResponseWriter
has been written to before I write to it with an easy method.
我正在寻找一个类似于以下内容的函数,可以在写入ResponseWriter
之前使用它:
I am looking for a function that would look something like the following which I can use before I write to the ResponseWriter
:
if w.Header().Get("Status-Code") == "" {
http.Redirect(w, r, "/", http.StatusSeeOther)
} else {
fmt.Println("Response Writer has already been written to.")
}
上面的代码似乎不起作用……任何人都不知道如何检查ResponseWriter
是否已写入?
The code above doesn't seem to work... anyone have any idea how to check if the ResponseWriter
has been written to or not?
推荐答案
唯一的方法是使用http.ResponseWriter
的自定义实现:
The only way to do this is with a custom implementation of 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
}
}
我还汇集了一个简单的包来为我处理这个问题.如果愿意,也可以随时使用它.
I also threw together a simple package to handle this for me. Feel free to use it as well if you like.
这篇关于如何检查ResponseWriter是否已编写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!