Files
mtusi2026lab5/internal/platform/httpx/respond.go
T

88 lines
2.8 KiB
Go

package httpx
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
type errorEnvelope struct {
Error errorDetail `json:"error"`
}
type errorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type statusCode struct {
status int
code string
}
var kinds = map[apperr.Kind]statusCode{
apperr.KindInvalid: {http.StatusBadRequest, "invalid_request"},
apperr.KindUnauthorized: {http.StatusUnauthorized, "unauthorized"},
apperr.KindNotFound: {http.StatusNotFound, "not_found"},
apperr.KindConflict: {http.StatusConflict, "conflict"},
apperr.KindPayloadTooLarge: {http.StatusRequestEntityTooLarge, "payload_too_large"},
apperr.KindUnsupportedMedia: {http.StatusUnsupportedMediaType, "unsupported_media_type"},
apperr.KindUnavailable: {http.StatusServiceUnavailable, "unavailable"},
}
// JSON is the single place that fixes the response media type; PureJSON
// keeps non-ASCII and HTML characters verbatim.
func JSON(c *gin.Context, status int, body any) {
c.PureJSON(status, body)
}
// Fail writes the contract error body and stops the handler chain.
func Fail(c *gin.Context, status int, code, message string) {
JSON(c, status, errorEnvelope{Error: errorDetail{
Code: code,
Message: message,
RequestID: RequestID(c),
}})
c.Abort()
}
// Error maps an application error to its status. Anything that is not an
// application error is logged with its text and reported as an opaque 500,
// so internal details never reach the client. An application error shows the
// client only its own message, never the context it was wrapped in on the
// way up; when it is answered with a 5xx (a dependency outage) the full
// chain and the cause go to the log for the operator.
func Error(c *gin.Context, err error) {
appErr, isApp := errors.AsType[*apperr.Error](err)
var mapped statusCode
known := false
if isApp {
mapped, known = kinds[appErr.Kind]
}
if !known {
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
return
}
if mapped.status >= http.StatusInternalServerError {
attrs := []any{"request_id", RequestID(c), "error", err.Error()}
if appErr.Cause != nil {
attrs = append(attrs, "cause", appErr.Cause.Error())
}
logger(c).Error("request failed", attrs...)
}
Fail(c, mapped.status, mapped.code, appErr.Message)
}
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
// (the oldest version the public tests support) only parses 3 or 6 fractional
// digits, and RFC3339Nano would trim trailing zeros to a variable width.
func Timestamp(t time.Time) string {
return t.UTC().Format("2006-01-02T15:04:05.000Z")
}