Skip to content

Instantly share code, notes, and snippets.

@prnvbn
Created September 23, 2021 12:13
Show Gist options
  • Save prnvbn/20b6a6e5739670a3d69722fe52d625fd to your computer and use it in GitHub Desktop.
Save prnvbn/20b6a6e5739670a3d69722fe52d625fd to your computer and use it in GitHub Desktop.
Utility functions for a mux REST API.
func respondWithErrorMsg(w http.ResponseWriter, code int, msg string) {
respondWithJSON(w, code, map[string]string{"error": msg})
}
func respondWithError(w http.ResponseWriter, code int, err error) {
respondWithJSON(w, code, map[string]string{"error": err.Error()})
}
// respondWithJSON converts the payload into JSON and responds with it
// payload can be struct or a map
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) error {
response, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("error marshalling payload %v", payload)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment