Created
April 20, 2020 19:26
-
-
Save drumer2142/e5b64ae57286b386b43d1d55832710bd to your computer and use it in GitHub Desktop.
Dynamic Error response calling respondJSON Func with the use of Interface for dynamic payload
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
package handler | |
import ( | |
"encoding/json" | |
"net/http" | |
) | |
// respondJSON makes the response with payload as json format | |
func respondJSON(w http.ResponseWriter, status int, payload interface{}) { | |
response, err := json.Marshal(payload) | |
if err != nil { | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte(err.Error())) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(status) | |
w.Write([]byte(response)) | |
} | |
// respondError makes the error response with payload as json format | |
func respondError(w http.ResponseWriter, code int, message string) { | |
respondJSON(w, code, map[string]string{"error": message}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment