forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// коды ошибок по контракту
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMediaType = "unsupported_media_type"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodeRateLimited = "rate_limited"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type ErrorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// ErrorResponse — строгое тело ответа при любой ошибке
|
||||
type ErrorResponse struct {
|
||||
Error ErrorPayload `json:"error"`
|
||||
}
|
||||
|
||||
// WriteJSON отправляет любой успешный ответ с правильными заголовками
|
||||
func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
if data != nil {
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке
|
||||
func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
resp := ErrorResponse{
|
||||
Error: ErrorPayload{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
Reference in New Issue
Block a user