How to check if ResponseWriter has been written

2019-07-24 09:00发布

问题:

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: multiple response.WriteHeader calls

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.

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.")
}

The code above doesn't seem to work... anyone have any idea how to check if the ResponseWriter has been written to or not?

回答1:

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.