Skip to content

Instantly share code, notes, and snippets.

@drumer2142
Created April 20, 2020 19:26
Show Gist options
  • Save drumer2142/e5b64ae57286b386b43d1d55832710bd to your computer and use it in GitHub Desktop.
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
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