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

51 lines
1.5 KiB
Go

// Package httpx is the transport layer over gin: request ids, access
// logging, panic recovery, body limits, strict JSON decoding and the single
// error format of the API contract. gin is used for routing and the
// middleware chain; everything here exists because the contract demands a
// specific behaviour that gin's own helpers do not provide.
package httpx
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
const (
keyRequestID = "messenger.request_id"
keyLogger = "messenger.logger"
)
// NewEngine builds an engine whose every response, including routing
// failures and panics, carries X-Instance-Id, X-Request-Id and the contract
// error body.
func NewEngine(log *slog.Logger, maxBodyBytes int64, instanceID string) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
e := gin.New()
// Redirects would answer with text/plain and without a request id.
e.RedirectTrailingSlash = false
e.RedirectFixedPath = false
e.HandleMethodNotAllowed = true
e.Use(instance(instanceID), requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
e.NoRoute(func(c *gin.Context) { Error(c, apperr.NotFound("route not found")) })
e.NoMethod(func(c *gin.Context) { Fail(c, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") })
return e
}
func RequestID(c *gin.Context) string {
return c.GetString(keyRequestID)
}
func logger(c *gin.Context) *slog.Logger {
if l, ok := c.Get(keyLogger); ok {
if log, ok := l.(*slog.Logger); ok {
return log
}
}
return slog.Default()
}