json response helpers
This commit is contained in:
@@ -0,0 +1,25 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func respondWithError(w http.ResponseWriter, code int, msg string) {
|
||||||
|
type returnVals struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
respondWithJSON(w, code, returnVals{Error: msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
func respondWithJSON(w http.ResponseWriter, code int, payload any) {
|
||||||
|
dat, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(code)
|
||||||
|
w.Write(dat)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user