Documentation
¶
Overview ¶
Package gin integrates Gin HTTP routing with Scene applications, dependency injection, request binding, middleware, and the common response envelope.
Applications ¶
AppRoutes is the usual entry point. It owns an application context, injects that context when the application is created, and mounts every action below BasePath:
app := &sgin.AppRoutes[appContext]{
AppName: moduleName.ImplNameNoVer("GinApplication"),
BasePath: "users",
Context: appContext{},
Actions: []sgin.Action[*appContext]{
new(getUserAction),
},
}
An action only needs route metadata and Process:
type healthAction struct{}
func (*healthAction) GetRoute() sgin.HttpRouteInfo {
return sgin.HttpRouteInfo{
Methods: sgin.HttpMethodGet,
Path: "/health",
}
}
func (*healthAction) Process(
ctx *sgin.Context[*appContext],
) (any, error) {
return map[string]string{"status": "ok"}, nil
}
Direct Gin registration ¶
Implement GinApplication directly when an endpoint should use Gin's native handlers without Action, binding, or Scene's response envelope. Create receives both the root *gin.Engine and a router already scoped by the container prefix and Prefix:
type rawGinApplication struct{}
func (*rawGinApplication) Name() scene.ImplName {
return moduleName.ImplNameNoVer("RawGinApplication")
}
func (*rawGinApplication) Prefix() string {
return "raw"
}
func (*rawGinApplication) Create(
engine *gin.Engine,
router gin.IRouter,
) error {
router.GET("/health", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// Register on engine only when the route should intentionally bypass
// the container and application prefixes.
engine.GET("/ready", func(ctx *gin.Context) {
ctx.Status(http.StatusNoContent)
})
return nil
}
func (*rawGinApplication) Destroy() error {
return nil
}
Binding ¶
Binding is optional. Embed RequestJson, RequestQuery, RequestURI, or another request helper for one source. Implement BindingProvider when an action needs multiple sources:
func (*updateUserAction) Bindings() []sgin.Binding {
return []sgin.Binding{
sgin.BindURI,
sgin.BindJSON,
}
}
Bindings run in declaration order. The explicit URI, query, JSON, and form bindings defer validation until every binding has populated the action, so binding:"required" works across multiple sources.
Middleware ¶
AppRoutes.Middlewares apply to every application action. An individual action can implement MiddlewareProvider to append route-specific middleware. Container middleware runs first, followed by application middleware, action middleware, and Process.
Context and responses ¶
Context embeds *gin.Context, exposes the injected application context as App, and implements context.Context by delegating cancellation and values to the request. Process results use Scene's common response envelope. An action that writes a streaming or otherwise custom response can return ErrAlreadyDone to prevent the default renderer from writing another body.
Index ¶
- Constants
- Variables
- func BindAuto(ctx *gin.Context, target any) error
- func BindForm(ctx *gin.Context, target any) error
- func BindFormURLEncoded(ctx *gin.Context, target any) error
- func BindJSON(ctx *gin.Context, target any) error
- func BindQuery(ctx *gin.Context, target any) error
- func BindURI(ctx *gin.Context, target any) error
- func Handle[T any](app T, action Action[T]) gin.HandlerFunc
- func NewAppContainer(addr string, apps []GinApplication, options ...GinOption) scene.Scene
- func NewAppContainerWithPrefix(addr string, prefix string, apps []GinApplication, options ...GinOption) scene.Scene
- type Action
- type AppRouter
- type AppRoutes
- type Binding
- type BindingProvider
- type Context
- type GinApplication
- type GinOption
- type HttpRoute
- type HttpRouteInfo
- type MiddlewareProvider
- type RequestAuto
- type RequestForm
- type RequestFormUrlEncoded
- type RequestJson
- type RequestQuery
- type RequestURI
Constants ¶
const ( HttpMethodGet uint16 = 0b1 HttpMethodHead uint16 = 0b10 HttpMethodPost uint16 = 0b100 HttpMethodPut uint16 = 0b1000 HttpMethodPatch uint16 = 0b10000 // RFC 5789 HttpMethodDelete uint16 = 0b100000 HttpMethodConnect uint16 = 0b1000000 HttpMethodOptions uint16 = 0b10000000 HttpMethodTrace uint16 = 0b100000000 )
HTTP method bitmap flags used by HttpRouteInfo.
Variables ¶
var ( // ErrAlreadyDone tells Handle that the action already wrote the response. ErrAlreadyDone = errcode.CreateError(100, "gin already done") )
Functions ¶
func BindAuto ¶ added in v0.3.7
BindAuto uses Gin's content-type and method based binding selection. It is intended for an action that uses one automatically selected source.
func BindFormURLEncoded ¶ added in v0.3.7
BindFormURLEncoded binds URL-encoded form values without validating target.
func Handle ¶
func Handle[T any](app T, action Action[T]) gin.HandlerFunc
Handle adapts an Action to a Gin handler.
action is a pointer prototype. Handle creates a fresh zero-valued action for every request so bound request data is never shared between requests.
func NewAppContainer ¶
func NewAppContainer( addr string, apps []GinApplication, options ...GinOption, ) scene.Scene
NewAppContainer creates a Gin scene mounted at the root path.
func NewAppContainerWithPrefix ¶
func NewAppContainerWithPrefix( addr string, prefix string, apps []GinApplication, options ...GinOption, ) scene.Scene
NewAppContainerWithPrefix creates a Gin scene mounted below prefix.
Types ¶
type Action ¶ added in v0.2.7
Action describes one HTTP endpoint.
Binding and middleware are optional. An action can additionally implement BindingProvider and MiddlewareProvider.
type AppRouter ¶ added in v0.2.7
type AppRouter[T any] struct { // contains filtered or unexported fields }
AppRouter registers actions for one application context.
func NewAppRouter ¶ added in v0.2.7
NewAppRouter creates a router for app and takes an immutable copy of the application middleware chain.
func (*AppRouter[T]) HandleAction ¶ added in v0.2.7
HandleAction registers every method declared by action's method bitmap.
func (*AppRouter[T]) HandleActions ¶ added in v0.2.7
HandleActions registers actions in order.
type AppRoutes ¶ added in v0.2.7
type AppRoutes[T any] struct { AppName scene.ImplName BasePath string Actions []Action[*T] Context T Middlewares gin.HandlersChain }
AppRoutes is the declarative GinApplication used by most modules.
Context is injected when Create is called. Middlewares apply to every action, before middleware supplied by an individual MiddlewareProvider.
type Binding ¶ added in v0.3.7
Binding binds one request source into target.
The explicit BindURI, BindQuery, BindJSON, and form bindings defer validation. Handle validates the action once after all declared bindings have run, so multiple request sources can populate the same action first.
type BindingProvider ¶ added in v0.3.7
type BindingProvider interface {
Bindings() []Binding
}
BindingProvider supplies request bindings in execution order.
type Context ¶
Context combines Gin's request context with an injected application context. It also implements context.Context.
func (*Context[T]) SetContextValue ¶ added in v0.3.6
type GinApplication ¶
type GinApplication interface {
scene.Application
Prefix() string
Create(engine *gin.Engine, router gin.IRouter) error
Destroy() error
}
GinApplication mounts one module's HTTP routes into a Gin scene.
Create receives the root Gin engine and a router scoped by the container prefix and Prefix. Most implementations should register routes on router.
type GinOption ¶
GinOption configures the Gin engine before applications are mounted.
func WithLogger ¶
WithLogger installs Scene's request logger.
type HttpRoute ¶ added in v0.3.2
type HttpRoute interface {
GetRoute() HttpRouteInfo
}
HttpRoute provides route metadata for an Action.
type HttpRouteInfo ¶ added in v0.3.2
HttpRouteInfo declares the methods and relative path of an action.
type MiddlewareProvider ¶ added in v0.3.7
type MiddlewareProvider interface {
Middleware() gin.HandlersChain
}
MiddlewareProvider supplies middleware that applies only to one action.
type RequestAuto ¶ added in v0.3.7
type RequestAuto struct{}
RequestAuto selects a binding from the request method and content type.
func (*RequestAuto) Bindings ¶ added in v0.3.7
func (*RequestAuto) Bindings() []Binding
type RequestForm ¶ added in v0.2.8
type RequestForm struct{}
RequestForm binds query and form values.
func (*RequestForm) Bindings ¶ added in v0.3.7
func (*RequestForm) Bindings() []Binding
type RequestFormUrlEncoded ¶ added in v0.2.8
type RequestFormUrlEncoded struct{}
RequestFormUrlEncoded binds a URL-encoded form body.
func (*RequestFormUrlEncoded) Bindings ¶ added in v0.3.7
func (*RequestFormUrlEncoded) Bindings() []Binding
type RequestJson ¶
type RequestJson struct{}
RequestJson binds a JSON request body.
func (*RequestJson) Bindings ¶ added in v0.3.7
func (*RequestJson) Bindings() []Binding
type RequestQuery ¶
type RequestQuery struct{}
RequestQuery binds URL query values.
func (*RequestQuery) Bindings ¶ added in v0.3.7
func (*RequestQuery) Bindings() []Binding
type RequestURI ¶
type RequestURI struct{}
RequestURI binds Gin route parameters.
func (*RequestURI) Bindings ¶ added in v0.3.7
func (*RequestURI) Bindings() []Binding