Documentation
¶
Overview ¶
Package ginx adapts svckit to the Gin framework.
Gin is the reason this package needs to exist. Where chi and the standard library's own mux consume svckit's middleware directly -- it is already func(http.Handler) http.Handler -- Gin has its own handler type, its own context and its own response writer, so each piece needs a translation:
router := gin.New()
router.Use(ginx.Route()) // label metrics by route template
router.Use(ginx.TracingMiddleware())
router.Use(ginx.PrometheusMiddleware("orders"))
router.Use(ginx.LoggingMiddleware())
It also carries the Gin expression of svckit/httpx -- the same response envelope, decoding and pagination semantics, written against gin.Context -- so handlers do not hand-roll a second set.
Use adapts any func(http.Handler) http.Handler into a gin.HandlerFunc, which covers svckit middleware this package does not wrap explicitly.
It lives in its own module so that the main svckit module depends on no web framework: importing svckit does not pull in Gin, and a project on a different Gin version is unaffected by what this module requires.
Index ¶
- func BadRequest(c *gin.Context, message string)
- func Bind(c *gin.Context, dst any) bool
- func CORSWithOrigins(allowedOrigins []string) gin.HandlerFunc
- func Created(c *gin.Context, v any)
- func EnablePprofIfDebug(router *gin.Engine)
- func Error(c *gin.Context, status int, message string)
- func ErrorCode(c *gin.Context, status int, message, code string)
- func GetAuthenticatedService(c *gin.Context) (string, bool)
- func GetClientIdentifier(c *gin.Context) string
- func GetTraceContext(c *gin.Context) *httpclient.TraceContext
- func HasServiceScope(c *gin.Context, scope string) bool
- func HealthCheck(serviceName string, checks ...webmw.HealthChecker) gin.HandlerFunc
- func InternalError(c *gin.Context, err error)
- func IsServiceAuthenticated(c *gin.Context) bool
- func LoggingMiddleware() gin.HandlerFunc
- func MetricsHandler() gin.HandlerFunc
- func NotFound(c *gin.Context, message string)
- func OK(c *gin.Context, v any)
- func OptionalServiceAuth(validator webmw.ServiceKeyValidator) gin.HandlerFunc
- func Pagination(c *gin.Context) httpx.Page
- func PaginationWith(c *gin.Context, defaultLimit, maxLimit int) httpx.Page
- func PrometheusMiddleware(serviceName string) gin.HandlerFunc
- func RateLimitMiddleware(redisClient *rediscluster.ClusterClient, serviceName string) gin.HandlerFunc
- func ReadinessCheck(serviceName string, checks ...webmw.HealthChecker) gin.HandlerFunc
- func RequestLoggingMiddleware(serviceName string) gin.HandlerFunc
- func RequireServiceScope(requiredScope string) gin.HandlerFunc
- func Route() gin.HandlerFunc
- func ServiceAuthOrUserAuth(validator webmw.ServiceKeyValidator, userAuthMiddleware gin.HandlerFunc) gin.HandlerFunc
- func ServiceAuthRequired(validator webmw.ServiceKeyValidator) gin.HandlerFunc
- func SetUserID(c *gin.Context, userID string)
- func TracingMiddleware() gin.HandlerFunc
- func Use(mw func(http.Handler) http.Handler) gin.HandlerFunc
- func UseThen(mw func(http.Handler) http.Handler, sync func(*gin.Context)) gin.HandlerFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BadRequest ¶
BadRequest responds 400 with the given public-safe message.
func Bind ¶
Bind decodes the JSON request body into dst. On failure it writes the standard 400 response and returns false — callers just early-return.
func CORSWithOrigins ¶
func CORSWithOrigins(allowedOrigins []string) gin.HandlerFunc
CORSWithOrigins is the Gin form of webmw.CORSWithOrigins.
func EnablePprofIfDebug ¶
EnablePprofIfDebug mounts the profiling endpoints on router when the debug gate is open. It is the Gin expression of debug.Register.
func Error ¶
Error responds with the standard error envelope. The message goes to the client verbatim — public-safe descriptions only, never err.Error() from an internal error (use InternalError for those).
func GetAuthenticatedService ¶
GetAuthenticatedService returns the calling service's name, if the request was authenticated as a service.
func GetClientIdentifier ¶
GetClientIdentifier returns the rate-limiting bucket for the request.
func GetTraceContext ¶
func GetTraceContext(c *gin.Context) *httpclient.TraceContext
GetTraceContext returns the trace context attached to c, or nil.
func HasServiceScope ¶
HasServiceScope reports whether the calling service holds scope. The wildcard scope satisfies any check.
func HealthCheck ¶
func HealthCheck(serviceName string, checks ...webmw.HealthChecker) gin.HandlerFunc
HealthCheck is the Gin form of webmw.HealthHandler.
func InternalError ¶
InternalError logs err with the request path for operators and responds with the canonical 500 — the client never sees the internal error string.
func IsServiceAuthenticated ¶
IsServiceAuthenticated reports whether the request was authenticated as a service rather than as a user.
func LoggingMiddleware ¶
func LoggingMiddleware() gin.HandlerFunc
LoggingMiddleware logs one line per completed request. It is Gin's equivalent of webmw.RequestLogging, kept separate because Gin records the status on its own writer rather than through a wrapper.
Output goes through slog's default logger, so these lines carry the established format. The service name is omitted because the handler already prefixes every line with it.
func MetricsHandler ¶
func MetricsHandler() gin.HandlerFunc
MetricsHandler serves the Prometheus exposition format.
func OptionalServiceAuth ¶
func OptionalServiceAuth(validator webmw.ServiceKeyValidator) gin.HandlerFunc
OptionalServiceAuth is the Gin form of webmw.OptionalServiceAuth.
func Pagination ¶
Pagination parses limit/offset query parameters with httpx's defaults and clamping.
func PaginationWith ¶
PaginationWith parses pagination with a custom default and maximum limit.
func PrometheusMiddleware ¶
func PrometheusMiddleware(serviceName string) gin.HandlerFunc
PrometheusMiddleware is the Gin form of webmw.Metrics. It reads the status from Gin's writer rather than wrapping it, and records through webmw's exported recorders so both forms share one set of series.
func RateLimitMiddleware ¶
func RateLimitMiddleware(redisClient *rediscluster.ClusterClient, serviceName string) gin.HandlerFunc
RateLimitMiddleware is the Gin form of webmw.RateLimit.
func ReadinessCheck ¶
func ReadinessCheck(serviceName string, checks ...webmw.HealthChecker) gin.HandlerFunc
ReadinessCheck is the Gin form of webmw.ReadinessHandler.
func RequestLoggingMiddleware ¶
func RequestLoggingMiddleware(serviceName string) gin.HandlerFunc
RequestLoggingMiddleware logs one line per completed request, reading the status from Gin's writer.
func RequireServiceScope ¶
func RequireServiceScope(requiredScope string) gin.HandlerFunc
RequireServiceScope is the Gin form of webmw.RequireServiceScope.
func Route ¶
func Route() gin.HandlerFunc
Route records Gin's matched route pattern on the request context so that webmw's metrics and logging label by route template rather than by concrete path. Register it before the middlewares that read it.
func ServiceAuthOrUserAuth ¶
func ServiceAuthOrUserAuth(validator webmw.ServiceKeyValidator, userAuthMiddleware gin.HandlerFunc) gin.HandlerFunc
ServiceAuthOrUserAuth accepts either a service API key or, failing that, whatever userAuthMiddleware accepts.
func ServiceAuthRequired ¶
func ServiceAuthRequired(validator webmw.ServiceKeyValidator) gin.HandlerFunc
ServiceAuthRequired is the Gin form of webmw.ServiceAuthRequired. It mirrors the validated identity onto gin.Context for handlers reading it from there.
func SetUserID ¶
SetUserID records the authenticated user on the request's trace context and on the request context, so rate limiting and outbound calls both see it.
func TracingMiddleware ¶
func TracingMiddleware() gin.HandlerFunc
TracingMiddleware is the Gin form of webmw.Tracing. It additionally mirrors the trace onto gin.Context under "trace_context" for handlers using GetTraceContext.
func Use ¶
Use adapts a standard net/http middleware — func(http.Handler) http.Handler, the form the toolkit packages are written in — into gin.HandlerFunc, so Gin routers can run framework-neutral middleware unchanged.
The adapter runs mw around a handler that resumes the Gin chain, so middleware that short-circuits (writing a response without calling the next handler) correctly aborts the remaining Gin handlers, and context values it attaches reach downstream handlers.
One kind of middleware does not survive the adaptation: one that substitutes the http.ResponseWriter to observe the response, since Gin handlers write through c.Writer and would bypass the substitute. Middleware that needs the response status — metrics and request logging — therefore has a dedicated Gin form in this package that reads the status from Gin's own writer.
func UseThen ¶
UseThen runs a stdlib middleware in a Gin chain and calls sync once the middleware has annotated the request but before the rest of the chain runs. It is how a Gin veneer mirrors context values onto gin.Context for handlers that still read them from there.
The mirroring has to happen at that point: Use resumes the whole Gin chain from inside the middleware, so anything written to gin.Context after Use returns lands after the route handler has already read it.
Types ¶
This section is empty.