gin

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 18 Imported by: 0

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

View Source
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

View Source
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

func BindAuto(ctx *gin.Context, target any) error

BindAuto uses Gin's content-type and method based binding selection. It is intended for an action that uses one automatically selected source.

func BindForm added in v0.3.7

func BindForm(ctx *gin.Context, target any) error

BindForm binds query and form values without validating target.

func BindFormURLEncoded added in v0.3.7

func BindFormURLEncoded(ctx *gin.Context, target any) error

BindFormURLEncoded binds URL-encoded form values without validating target.

func BindJSON added in v0.3.7

func BindJSON(ctx *gin.Context, target any) error

BindJSON decodes a JSON request body without validating target.

func BindQuery added in v0.3.7

func BindQuery(ctx *gin.Context, target any) error

BindQuery binds URL query values without validating target.

func BindURI added in v0.3.7

func BindURI(ctx *gin.Context, target any) error

BindURI binds Gin route parameters 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

type Action[T any] interface {
	Process(ctx *Context[T]) (data any, err error)
	HttpRoute
}

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

func NewAppRouter[T any](app T, router gin.IRouter, middlewares gin.HandlersChain) *AppRouter[T]

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

func (r *AppRouter[T]) HandleAction(action Action[T])

HandleAction registers every method declared by action's method bitmap.

func (*AppRouter[T]) HandleActions added in v0.2.7

func (r *AppRouter[T]) HandleActions(actions ...Action[T])

HandleActions registers actions in order.

func (*AppRouter[T]) Router added in v0.2.7

func (r *AppRouter[T]) Router() gin.IRouter

Router returns the underlying Gin router.

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.

func (*AppRoutes[T]) Create added in v0.2.7

func (a *AppRoutes[T]) Create(engine *gin.Engine, router gin.IRouter) error

func (*AppRoutes[T]) Destroy added in v0.2.7

func (a *AppRoutes[T]) Destroy() error

func (*AppRoutes[T]) Name added in v0.2.7

func (a *AppRoutes[T]) Name() scene.ImplName

func (*AppRoutes[T]) Prefix added in v0.2.7

func (a *AppRoutes[T]) Prefix() string

type Binding added in v0.3.7

type Binding func(ctx *gin.Context, target any) error

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

type Context[T any] struct {
	*gin.Context
	App T // App is the container of current app
}

Context combines Gin's request context with an injected application context. It also implements context.Context.

func (*Context[T]) Deadline added in v0.3.6

func (g *Context[T]) Deadline() (deadline time.Time, ok bool)

func (*Context[T]) Done added in v0.3.6

func (g *Context[T]) Done() <-chan struct{}

func (*Context[T]) Err added in v0.3.6

func (g *Context[T]) Err() error

func (*Context[T]) SetContextValue added in v0.3.6

func (g *Context[T]) SetContextValue(key any, value any)

func (*Context[T]) Value added in v0.3.6

func (g *Context[T]) Value(key any) any

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

type GinOption func(engine *gin.Engine) error

GinOption configures the Gin engine before applications are mounted.

func WithCors

func WithCors() GinOption

WithCors allows all origins and request headers.

func WithGzip added in v0.2.8

func WithGzip(level int) GinOption

WithGzip add gzip support for gin engine, default level is -1

func WithLogger

func WithLogger(log logger.ILogger) GinOption

WithLogger installs Scene's request logger.

func WithRecovery

func WithRecovery() GinOption

WithRecovery installs Gin's recovery middleware.

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

type HttpRouteInfo struct {
	Methods uint16
	Path    string
}

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

Jump to

Keyboard shortcuts

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