34 lines
928 B
Go
34 lines
928 B
Go
// 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")
|
|
}
|
|
}
|