mirror of
https://github.com/kevin-DL/football_info_api.git
synced 2026-01-22 14:35:29 +00:00
Initial commit
This commit is contained in:
34
helpers/json.go
Normal file
34
helpers/json.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func RespondWithError(w http.ResponseWriter, code int, msg string) {
|
||||
if code > 499 {
|
||||
log.Println("Responding with 5XX error: ", msg)
|
||||
}
|
||||
|
||||
type errResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
RespondWithJson(w, code, errResponse{
|
||||
Error: msg,
|
||||
})
|
||||
}
|
||||
|
||||
func RespondWithJson(w http.ResponseWriter, code int, payload interface{}) {
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
log.Printf("Failed to marshall JSON response: %v", payload)
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
w.Write(data)
|
||||
}
|
||||
Reference in New Issue
Block a user