3 ms·
Good advice! A small addition in the third point: you can create a separate interface for HTTP errors, for example: type HTTPError interface { GetH
by mcdoker18 6y ago
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.