servergin

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package server 运行时适配器:把统一路由注册表(routes.All())挂载到原生 Gin。 职责:上下文装饰 -> 参数绑定 -> 入参转换 -> 校验 -> Handler 调用 -> 出参转换 -> 状态码决策 -> 响应壳包装 -> 写出。 设计目标:业务层零框架依赖;解析/校验/错误映射/响应壳均可扩展。

Index

Constants

View Source
const CodeError = response.CodeError

CodeError 业务错误码

Variables

This section is empty.

Functions

func FailWithCode

func FailWithCode(c *gin.Context, code int, msg string)

FailWithCode 业务错误:自定义 code(默认壳)

func FailWithMessage

func FailWithMessage(c *gin.Context, msg string)

FailWithMessage 业务错误:HTTP 200 + code=7 + msg(默认壳)

func Ok

func Ok(c *gin.Context)

Ok 成功(data 为 null)

func OkWithData

func OkWithData(c *gin.Context, data any)

OkWithData 成功 + 数据(默认壳 {code, data, msg})

func OkWithDataStatus

func OkWithDataStatus(c *gin.Context, status int, data any)

OkWithDataStatus 成功 + 数据 + 自定义状态码(默认壳)

Types

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server 运行时服务器装配器

func New

func New() *Server

New 创建 Server

func (*Server) AddValidator

func (s *Server) AddValidator(v validator.Func) *Server

AddValidator 扩展点:注册自定义校验器(绑定后执行), 见 validator 包:内置标签必填 + Validate() 接口调用;validator.Playground() 接入完整校验规则

func (*Server) Mount

func (s *Server) Mount(g *gin.RouterGroup, groups []*contract.Group)

Mount 把路由分组树挂载到 gin.RouterGroup。 组中间件就地断言为 gin.HandlerFunc 后 Use(gin 自动向子组继承)。

func (*Server) SetBindErrorStatus

func (s *Server) SetBindErrorStatus(status int) *Server

SetBindErrorStatus 扩展点:设置参数绑定/校验失败(含 InTransform 错误)的 HTTP 状态码。 默认 200(存量行为:HTTP 200 + code=CodeError);设为 400 可获得 RESTful 语义, 非 200 时业务 code 跟随状态码(与 StatusError 约定一致)。 仅影响绑定/校验阶段;Handler 返回的业务错误走 StatusError / SetErrorMapper,不受影响。

func (*Server) SetContextDecorator

func (s *Server) SetContextDecorator(fn func(c *gin.Context, ctx context.Context) context.Context) *Server

SetContextDecorator 扩展点:把 gin 上下文信息注入 context.Context。 在每次请求最前执行(Q/B 绑定之前),TransformIn / 校验器 / TransformOut / handler 共享同一个已装饰 ctx。约定:fn 必须是纯派生(只读 c、轻量 WithValue 级操作), 重操作(鉴权、查库)请放中间件——每个请求(含校验失败的请求)都会执行。

func (*Server) SetEnvelope

func (s *Server) SetEnvelope(env response.Envelope) *Server

SetEnvelope 扩展点:自定义响应壳。 传入 nil 恢复默认壳 {code, data, msg};路由级覆盖见 contract.RouteMeta.Envelope。 文档侧请用 openapi.OptionWithEnvelopeSchema 配对配置(两者独立)。

func (*Server) SetErrorMapper

func (s *Server) SetErrorMapper(fn func(err error) (httpStatus, bizCode int)) *Server

SetErrorMapper 扩展点:自定义 错误 -> (HTTP状态码, 业务code) 映射。 仅对不携带状态码的普通错误生效(StatusError / StatusCoder 优先)。

func (*Server) Use

func (s *Server) Use(mw ...gin.HandlerFunc) *Server

Use 扩展点:挂载全局中间件(鉴权/CORS/限流等),在业务路由之前执行。 按分组挂载的中间件请直接写在 contract.Group.Middlewares(随树继承)。

Jump to

Keyboard shortcuts

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