Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Last active December 8, 2019 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhewedy/a0704a53d9bbfbc04f5abb51ac2f0ed9 to your computer and use it in GitHub Desktop.
Save mhewedy/a0704a53d9bbfbc04f5abb51ac2f0ed9 to your computer and use it in GitHub Desktop.
Separate serialization and error handling from the actual api handling logic in golang
type handlerFunc func(w http.ResponseWriter, r *http.Request) (interface{}, error)
func handle(fn handlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
i, err := fn(w, r)
if err != nil {
handleError(w, err, http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(i)
}
}
func handleError(w http.ResponseWriter, err error, code int) {
fmt.Fprintln(os.Stderr, err.Error())
w.WriteHeader(code)
json.NewEncoder(w).Encode(struct {
Error string `json:"error"`
StatusCode int `json:"status_code"`
}{
Error: err.Error(),
StatusCode: code,
})
}
// see an example usage: https://github.com/mhewedy/mego/blob/e77fff47c4b9a19965246a29c818c3d316b462b3/mego-api/api/routes.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment