Created
September 23, 2021 12:13
-
-
Save prnvbn/20b6a6e5739670a3d69722fe52d625fd to your computer and use it in GitHub Desktop.
Utility functions for a mux REST API.
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
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