News for hackers. Stuff that matters.
Re:REST Servers in Go: Part 1 – standard library by mcdoker18 on Sunday January 17, 2021 @08:34AM (#25810509)
Good advice! A small addition in the third point: you can create a separate interface for HTTP errors, for example:

    type HTTPError interface {
        GetHTTPCode() int
    }
    func ServeHTTP(w http.ResponseWriter, req \*http.Request) {
        result, err := DoTheActualThing()
        if err != nil {
            statusCode := http.StatusInternalServerError
            if httpError, ok := err.(HTTPError); ok {
                statusCode = httpError.GetHTTPCode()
            }
            http.Error(w, ..., statusCode)
            return
        }
        w.Header().Set("content-type", "application/json")
        w.WriteHeader(http.StatusOK)
        w.Write(result)
    }
You can apply the same approach for the HTTP body in case of error.

There are no comments on this comment yet.