如何检查ResponseWriter是否已编写 [英] How to check if ResponseWriter has been written

查看:75
本文介绍了如何检查ResponseWriter是否已编写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆