errors.go 590 B

123456789101112131415161718192021222324252627282930
  1. package server
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type apiError struct {
  7. Code string `json:"code"`
  8. Message string `json:"message"`
  9. }
  10. type errorEnvelope struct {
  11. Error apiError `json:"error"`
  12. }
  13. func writeError(w http.ResponseWriter, status int, code string, message string) {
  14. writeJSON(w, status, errorEnvelope{
  15. Error: apiError{
  16. Code: code,
  17. Message: message,
  18. },
  19. })
  20. }
  21. func writeJSON(w http.ResponseWriter, status int, value any) {
  22. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  23. w.WriteHeader(status)
  24. _ = json.NewEncoder(w).Encode(value)
  25. }