Files
Messenger/server/internal/api/respond.go
T

44 lines
1.2 KiB
Go
Raw Normal View History

// Package api implements the HTTP handlers for the messenger REST API.
package api
import (
"encoding/json"
"errors"
"net/http"
"messenger/internal/store"
)
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(body); err != nil {
http.Error(w, `{"error":"failed to encode response"}`, http.StatusInternalServerError)
}
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
func writeStoreError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrNotFound):
writeError(w, http.StatusNotFound, "not found")
case errors.Is(err, store.ErrDuplicate):
writeError(w, http.StatusConflict, "already exists")
default:
writeError(w, http.StatusInternalServerError, "internal server error")
}
}
// decodeJSON parses the request body into dst, rejecting oversized payloads.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
if err := json.NewDecoder(r.Body).Decode(dst); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return false
}
return true
}