ginx

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func BadRequest

func BadRequest(c *gin.Context, message string)

BadRequest responds 400 with the given public-safe message.

func Bind

func Bind(c *gin.Context, dst any) bool

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 Created

func Created(c *gin.Context, v any)

Created responds 201 with v as JSON.

func EnablePprofIfDebug

func EnablePprofIfDebug(router *gin.Engine)

EnablePprofIfDebug mounts the profiling endpoints on router when the debug gate is open. It is the Gin expression of debug.Register.

func Error

func Error(c *gin.Context, status int, message string)

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 ErrorCode

func ErrorCode(c *gin.Context, status int, message, code string)

ErrorCode responds with the standard error envelope plus a machine-readable code.

func GetAuthenticatedService

func GetAuthenticatedService(c *gin.Context) (string, bool)

GetAuthenticatedService returns the calling service's name, if the request was authenticated as a service.

func GetClientIdentifier

func GetClientIdentifier(c *gin.Context) string

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

func HasServiceScope(c *gin.Context, scope string) bool

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

func InternalError(c *gin.Context, err error)

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

func IsServiceAuthenticated(c *gin.Context) bool

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 NotFound

func NotFound(c *gin.Context, message string)

NotFound responds 404 with the given public-safe message.

func OK

func OK(c *gin.Context, v any)

OK responds 200 with v as JSON.

func OptionalServiceAuth

func OptionalServiceAuth(validator webmw.ServiceKeyValidator) gin.HandlerFunc

OptionalServiceAuth is the Gin form of webmw.OptionalServiceAuth.

func Pagination

func Pagination(c *gin.Context) httpx.Page

Pagination parses limit/offset query parameters with httpx's defaults and clamping.

func PaginationWith

func PaginationWith(c *gin.Context, defaultLimit, maxLimit int) httpx.Page

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

func SetUserID(c *gin.Context, userID string)

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

func Use(mw func(http.Handler) http.Handler) gin.HandlerFunc

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

func UseThen(mw func(http.Handler) http.Handler, sync func(*gin.Context)) gin.HandlerFunc

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL