package httpapi import ( "encoding/json" "net/http" ) const ( errorCodeInvalidRequest = "invalid_request" errorCodeUnauthorized = "unauthorized" errorCodeNotFound = "not_found" errorCodeInternal = "internal_error" errorCodeUnsupportedMediaType = "unsupported_media_type" errorCodePayloadTooLarge = "payload_too_large" errorCodeUnavailable = "unavailable" errorCodeConflict = "conflict" errorCodeRateLimited = "rate_limited" ) type apiError struct { status int code string message string } func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError { w.Header().Set("Allow", allowed) return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"} } func invalidRequest() *apiError { return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"} } func unauthorized() *apiError { return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"} } func notFound() *apiError { return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"} } func internalError() *apiError { return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"} } func unavailable() *apiError { return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"} } func writeError(w http.ResponseWriter, requestID string, err *apiError) { writeJSON(w, err.status, map[string]any{"error": map[string]string{ "code": err.code, "message": err.message, "request_id": requestID, }}) } 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) }