Check errors when calling http.ResponseWriter.Write()

Viewed 9001

Say I have this http handler:

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := GetSomeData()
    _, err := w.Write(data)
}

Should I check the error returned by w.Write? Examples I've seen just ignore it and do nothing. Also, functions like http.Error() do not return an error to be handled.

2 Answers

I want to add to @icza solution. You don't need to create logging structure, you can use simple function:

func logWrite(write func([]byte) (int, error), body []byte) {
    _, err := write(body)
    if err != nil {
        log.Printf("Write failed: %v", err)
    }
}

Take a look on that approach based on the @icza code: https://play.golang.org/p/PAetVixCgv4

Related