33 lines
974 B
Go
33 lines
974 B
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
func decodeJSON(r *http.Request, destination any) error {
|
|
decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(destination); err != nil {
|
|
return err
|
|
}
|
|
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
|
return errors.New("request body must contain one JSON object")
|
|
}
|
|
return nil
|
|
}
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|
|
func writeError(w http.ResponseWriter, status int, message string) {
|
|
writeJSON(w, status, map[string]any{"error": map[string]string{"message": message}})
|
|
}
|
|
|
|
func writeCodedError(w http.ResponseWriter, status int, code, message string) {
|
|
writeJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
|
|
}
|