Last active
December 8, 2019 08:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://github.com/mhewedy/mego/blob/e77fff47c4b9a19965246a29c818c3d316b462b3/mego-api/api/routes.go