router

package
v0.0.0-...-3432087 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

路由包使用说明

基础说明

为什么要二次封装

二次封装的想法来源于 web框架GoFrame。gf框架本身内置集成了大量组件, 对于轻量应用开发, 相比较而言比较笨重, 但是启根据请求数据结构、响应数据结构自动生成表单的能力十分实用。 在采用gin开发时,一般接口文档有两种选择 :

  • 在内部文档平台手搓文档, 并人工维护, 此方案最终演变方式大概率为文档主键滞后,与接口实现并不一致
  • 利用golang的文档生成工具swag 自动生成swagger文档, 此种方案需要在代码中引入大量swag工具解析时需要的注释, 且当输入/输出发生变化时需要维护相关注释 基于以上问题, 对gin的路由注册进行二次封装

二次封装解决哪些问题

  • 文档维护的繁琐性 : 会通过反射自动基于 请求的数据结构 + 返回的数据结构 , 生成接口文档, 专注于数据结构设计即可, 无需关注文档相关内容, 程序接管, 自动生成
  • 做接口设计的统一性规范约束, 如 :
    • 入参数据类型不能为 any
    • 入参类型不能为 map , 但是特定字段特定场景, 可以强行禁用此规则等
    • 返回值必须为结构体等

设计方案

【可选】路由组定义

路由组可以通过函数进行定义, 函数名必须需为 : RouterPrefix , 函数无任何参数, 返回路由组名称, 示例 :

type TestController struct{}

func (t *TestController) RouterPrefix() string {
	return "/uri/prefix"
}
【可选】路由组中间件定义

路由组中间件可以通过函数进行定义, 函数名必须需为 : RouterMiddleware , 函数无任何参数, 返回路由组中间件列表 []gin.HandlerFunc, 示例 :

type TestController struct{}

func (t *TestController) RouterPrefix() string {
	return "/uri/prefix"
}

func (t *TestController) RouterMiddleware() []gin.HandlerFunc {
	return []gin.HandlerFunc{
		func(ctx *gin.Context) {

		},
	}
}
接口逻辑处理定义

接口逻辑处理函数, 函数名称自定义, 必须是个 可导出函数 , 函数接收两个参数, 分别是 :

  • *gin.Context : gin框架的上下文信息
  • any: 表单参数 结构体指针 , 注意 : 类型必须为结构体指针

函数返回值有两个 :

  • any : 返回的业务数据, 必须是个 结构体指针
  • error : 可以是内置的 error , 也可以是 exception.IException , 建议使用 exception.IException , 可承载更多的异常信息

使用方式

type TestController struct{}

func (t *TestController) RouterPrefix() string {
	return "/uri/prefix"
}

func (t *TestController) RouterMiddleware() []gin.HandlerFunc {
	return []gin.HandlerFunc{
		func(ctx *gin.Context) {

		},
	}
}
func (t *TestController) Uri(ctx *gin.Context, formData *TestForm) (any, error) {
	return formData, nil
}

type TestForm struct {
	Meta `tag:"测试表单" path:"/a/b/c/d" desc:"测试接口" method:"get" strict:"true"`
	Age  int    `json:"age" form:"age"`
	Name string `json:"name" form:"name"`
	Test *Test  `json:"test" form:"test"`
	Num  *int64 `json:"num" form:"num"`
}
type Test struct {
	L string `json:"l"`
}

func Test_parseController(t *testing.T) {
	type args struct {
		controller any
	}
	Register(8080, &TestController{})
}

注意事项:

  • Register 方法第一个入参是监听的端口
  • 后面若干个controller实例, 朱一必须以指针的方式传入

Documentation

Overview

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-02-07 17:41

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-01-27 15:29

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2024-07-20 22:57

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-02-14 21:48

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-01-27 19:42

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2024-07-20 21:40

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-02-18 17:26

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2024-07-20 21:39

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-02-07 18:19

Package router ...

Description : router ...

Author : go_developer@163.com<白茶清欢>

Date : 2025-02-07 17:36

Index

Constants

View Source
const (
	PrefixFuncName         = "RouterPrefix"     // 路由前缀函数名称
	MiddlewareFuncName     = "RouterMiddleware" // 路由中间件函数名称
	GinContextType         = "*gin.Context"     // gin context 类型名称
	ErrorType              = "error"            // error类型
	ErrorInterfaceFuncName = "Error"            // error接口需要实现的方法名称
)
View Source
const (
	TagNamePath         = "path"          // 接口的请求路径
	TagNameMethod       = "method"        // 接口的请求方法
	TagNameUriTag       = "tag"           // 接口的tag
	TagNameDesc         = "desc"          // 接口的描述
	TagNameOutputStrict = "output_strict" // 接口数据是否为严格模式 : 严格模式, 响应数据必须是结构体/map,非严格模式返回任意值
	TagNameBinding      = "binding"       // gin 内置的验证规则tag
	TagNameValidate     = "validate"      // validator v10 默认的验证规则tag
	TagNameErrMsg       = "err"           // 验证失败错误信息tag
)
View Source
const (
	FieldNameMeta = "Meta" // 元信息字段
)

Variables

View Source
var (
	Debug = false // 是否开启DEBUG

)

Functions

func GetValidateErr

func GetValidateErr(obj any, rawErr error) error

GetValidateErr 格式化错误信息

Author : go_developer@163.com<白茶清欢>

Date : 22:19 2025/1/15

func NewServer

func NewServer(port int, optionList ...SetServerOptionFunc) *server

NewServer server实例

Author : go_developer@163.com<白茶清欢>

Date : 18:20 2025/2/7

func Register

func Register(port int, controllerList ...any) error

Register 注册路由

Author : go_developer@163.com<白茶清欢>

Date : 21:40 2024/7/20

func RequestHandler

func RequestHandler(uriCfg UriConfig) gin.HandlerFunc

RequestHandler 获取请求处理方法

Author : go_developer@163.com<白茶清欢>

Date : 19:44 2025/1/27

func SetValidateErrTag

func SetValidateErrTag(tagName string)

SetValidateErrTag 设置验证失败时, 获取错误信息的tag字段

Author : go_developer@163.com<白茶清欢>

Date : 17:42 2025/2/7

Types

type Doc

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

func NewDoc

func NewDoc(info *define.Info, servers []*define.ServerItem) *Doc

func (*Doc) Add

func (d *Doc) Add(routePrefix string, paramType reflect.Type, resultType reflect.Type)

Add 增加接口文档测试

Author : go_developer@163.com<白茶清欢>

Date : 21:55 2025/2/14

func (*Doc) Data

func (d *Doc) Data() *define.OpenapiDoc

Data 文档数据

Author : go_developer@163.com<白茶清欢>

Date : 21:59 2025/2/14

type Meta

type Meta struct{}

Meta 接口的元信息, 主要包含如下信息:

uri: 接口路由(不包含group前缀)

method: 请求方法: get/post 等

Author : go_developer@163.com<白茶清欢>

Date : 21:40 2024/7/20

type SetServerOptionFunc

type SetServerOptionFunc func(so *serverOption)

func WithDisableSwaggerDoc

func WithDisableSwaggerDoc() SetServerOptionFunc

WithDisableSwaggerDoc 禁用swagger文档

Author : go_developer@163.com<白茶清欢>

Date : 17:35 2025/2/18

func WithEnableCors

func WithEnableCors() SetServerOptionFunc

WithEnableCors 启用全局跨域

Author : go_developer@163.com<白茶清欢>

Date : 14:56 2025/2/22

func WithEnableRequestInit

func WithEnableRequestInit() SetServerOptionFunc

WithEnableRequestInit 全局配置初始化

Author : go_developer@163.com<白茶清欢>

Date : 14:56 2025/2/22

func WithGlobalMiddlewareList

func WithGlobalMiddlewareList(middlewareList ...gin.HandlerFunc) SetServerOptionFunc

WithGlobalMiddlewareList 设置全局中间件

Author : go_developer@163.com<白茶清欢>

Date : 17:33 2025/2/18

func WithLoggerCfg

func WithLoggerCfg(loggerCfg *middleware.AccessConfig) SetServerOptionFunc

WithLoggerCfg ...

Author : go_developer@163.com<白茶清欢>

Date : 15:25 2025/2/22

func WithPprofEnable

func WithPprofEnable() SetServerOptionFunc

WithPprofEnable 启用pprof

Author : go_developer@163.com<白茶清欢>

Date : 15:10 2025/2/21

func WithServerInfo

func WithServerInfo(serverInfo *apiDocDefine.Info) SetServerOptionFunc

WithServerInfo 设置serverInfo

Author : go_developer@163.com<白茶清欢>

Date : 17:51 2025/2/18

func WithServerList

func WithServerList(serverList []*apiDocDefine.ServerItem) SetServerOptionFunc

WithServerList 设置服务器列表

Author : go_developer@163.com<白茶清欢>

Date : 17:52 2025/2/18

func WithSwaggerBaseUri

func WithSwaggerBaseUri(baseUri string) SetServerOptionFunc

WithSwaggerBaseUri ...

Author : go_developer@163.com<白茶清欢>

Date : 18:05 2025/2/18

func WithSwaggerUITheme

func WithSwaggerUITheme(uiTheme string) SetServerOptionFunc

WithSwaggerUITheme 设置swaggerUI主题

Author : go_developer@163.com<白茶清欢>

Date : 17:29 2025/2/18

type UriConfig

type UriConfig struct {
	Path           string         `json:"path"`           // 接口路由, 必须配置
	RequestMethod  string         `json:"request_method"` // 接口请求方法, 必须配置
	TagList        []string       `json:"tag_list"`       // 接口分组
	Desc           string         `json:"desc"`           // 接口描述
	OutputStrict   bool           `json:"output_strict"`  // 接口是否为严格模式 : 不配置,可返回任意类型, 配置, 必须返回结构体或者map
	FormDataType   reflect.Type   `json:"-"`              // 表单数据类型
	ResultDataType reflect.Type   `json:"-"`              // 返回值数据类型
	ApiStructValue reflect.Value  `json:"-"`              // 逻辑函数所属结构体取值
	ApiLogicFunc   reflect.Method `json:"-"`              // 自定义的接口逻辑
}

UriConfig 接口配置

Author : go_developer@163.com<白茶清欢>

Date : 15:41 2024/7/21

type UriParam

type UriParam struct {
	Field           string `json:"field"`             // 结构体字段
	Name            string `json:"name"`              // 参数名称
	Type            string `json:"type"`              // 参数类型
	Validate        string `json:"validate"`          // 验证规则: validator/v10 库
	ErrorMsg        string `json:"error_msg"`         // 验证失败的错误信息
	DisableAutoType bool   `json:"disable_auto_type"` // 禁用自动类型转换
	Sort            string `json:"sort"`              // 参数读取顺序: 默认 POST : body > query > path GET : query > path > body
}

UriParam 接口参数配置

Author : go_developer@163.com<白茶清欢>

Date : 15:40 2025/1/27

Jump to

Keyboard shortcuts

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