Files
dizi b5583a813e
Skeleton contracts / contracts (push) Failing after 40s
Skeleton contracts / contracts (pull_request) Failing after 38s
chore: import lab2 baseline
2026-10-02 15:50:49 +03:00

61 lines
1.7 KiB
Go

package messenger
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"
)
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)
}