cygin

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2025 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrCodeInternal     = 101001
	ErrCodeNotFound     = 101404
	ErrCodeInvalidParam = 201001
)

---------- 错误码 ----------

View Source
const (
	LangEN = "en"
	LangZH = "zh"
)

支持的语言

View Source
const INDEX = "index.html"

Variables

View Source
var (
	BuildVersion = "dev"
	BuildTime    = "unknown"
)

==================== 全局变量(用于注入版本)====================

Functions

func BindAll

func BindAll(c *gin.Context, obj any, bindType BindType) error

BindAll 尝试从多个来源绑定数据到结构体 支持: URI, Query/Form, JSON, Header, File

func BindAndValidate

func BindAndValidate(c *gin.Context, obj interface{}) error

BindAndValidate 绑定请求并验证

func BindJSONAndValidate

func BindJSONAndValidate(c *gin.Context, obj interface{}) error

BindJSONAndValidate 绑定 JSON 并验证

func BindQueryAndValidate

func BindQueryAndValidate(c *gin.Context, obj interface{}) error

BindQueryAndValidate 绑定查询参数并验证

func FromCtx

func FromCtx(c *gin.Context) string

---------- 工具 ----------

func GetValidator

func GetValidator() *validator.Validate

GetValidator 返回全局验证器实例

func Handle

func Handle[
	Req any,
	Rsp any,
](fn func(c *gin.Context, req Req) (Rsp, error), cb ...cbZeroIO) gin.HandlerFunc

通用版本:可返回数据

func HandleAny

func HandleAny(fn any, cb ...cbZeroIO) (gin.HandlerFunc, error)

func HandleNoResp

func HandleNoResp[Req any](fn func(c *gin.Context, req Req, cb ...cbZeroIO) error) gin.HandlerFunc

func LocalFile

func LocalFile(root string, indexes bool) *localFileSystem

func RegErrMsg

func RegErrMsg(code int, fn func(lang string) string)

RegErrMsg allows overriding error message function for a code

func RegErrMsgStatic

func RegErrMsgStatic(code int, kvs ...string)

RegErrMsgStatic registers static messages for multiple languages Usage: RegErrMsgStatic(10001, "zh", "用户不存在", "en", "User not found")

func RegisterMessages

func RegisterMessages(msgs map[int]map[string]string)

RegisterMessages registers multiple error codes at once Usage:

cygin.RegisterMessages(map[int]map[string]string{
    10001: {"zh": "登录失败", "en": "Login failed"},
})

func Serve

func Serve(urlPrefix string, fs ServeFileSystem, isGroupPath ...funcIsGroupPath) gin.HandlerFunc

Static returns a middleware handler that serves static files in the given directory. For non-existent routes, it returns the index.html file to support SPA routing.

func ServeRoot

func ServeRoot(urlPrefix, root string) gin.HandlerFunc

func SetDefaultSuccessCode

func SetDefaultSuccessCode(code int)

func SetupValidator

func SetupValidator()

SetupValidator 设置 Gin 使用 go-playground/validator/v10

func ValidateStruct

func ValidateStruct(obj any) error

ValidateStruct 验证结构体

func ValidateStructWithLang

func ValidateStructWithLang(obj any, lang string) error

ValidateStructWithLang 验证结构体并返回国际化错误消息

Types

type APIHandler

type APIHandler interface {
	RegistRouter(basePath string, g *gin.RouterGroup) *RegistResult
}

type ApiEndpoint

type ApiEndpoint struct {
	Path        string
	Method      ApiMethod
	Summary     string
	Description string
	Tags        []string
	Handler     any
	Middleware  []gin.HandlerFunc
}

func (*ApiEndpoint) RegistRouter

func (ae *ApiEndpoint) RegistRouter(basePath string, g *gin.RouterGroup) *RegistResult

type ApiGroup

type ApiGroup struct {
	BasePath    string
	Description string
	Tags        []string
	Middleware  []gin.HandlerFunc
	APIHandler  []APIHandler
}

func (*ApiGroup) RegistRouter

func (ag *ApiGroup) RegistRouter(basePath string, g *gin.RouterGroup) *RegistResult

type ApiMethod

type ApiMethod string
const (
	Get     ApiMethod = "GET"
	Post    ApiMethod = "POST"
	Put     ApiMethod = "PUT"
	Delete  ApiMethod = "DELETE"
	Patch   ApiMethod = "PATCH"
	Options ApiMethod = "OPTIONS"
	Head    ApiMethod = "HEAD"
	Any     ApiMethod = "ANY"
)

type BindType

type BindType = int
const (
	BindTypeNone   BindType = 0
	BindTypeUri    BindType = 1 << 1
	BindTypeQuery  BindType = 1 << 2
	BindTypeForm   BindType = 1 << 3
	BindTypeJson   BindType = 1 << 4
	BindTypeHeader BindType = 1 << 5
	BindTypeFile   BindType = 1 << 6
	BindTypeAll    BindType = BindTypeUri | BindTypeQuery | BindTypeForm | BindTypeJson | BindTypeHeader | BindTypeFile
)

type Config

type Config struct {
	Address       string
	Env           string
	EnablePprof   bool
	EnableSwagger bool
	Title         string
	Version       string
	Description   string
	AutoRegister  bool
	// contains filtered or unexported fields
}

type EmbeddedFileConfig

type EmbeddedFileConfig struct {
	UrlPath string
	FS      embed.FS
	Root    string
}

type Endpoint

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

Endpoint 创建一个基础端点

func (Endpoint) Build

func (e Endpoint) Build() ApiEndpoint

Build 构建最终的 ApiEndpoint

func (Endpoint) WithDescription

func (e Endpoint) WithDescription(description string) Endpoint

WithDescription 设置端点描述

func (Endpoint) WithSummary

func (e Endpoint) WithSummary(summary string) Endpoint

WithSummary 设置端点摘要

func (Endpoint) WithTags

func (e Endpoint) WithTags(tags ...string) Endpoint

WithTags 设置端点标签

type EndpointBuilder

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

EndpointBuilder 是一个用于构建 API 端点的辅助函数集合

func NewEndpointBuilder

func NewEndpointBuilder(basePath string, description string, tags []string) *EndpointBuilder

NewEndpointBuilder 创建一个新的端点构建器

func (*EndpointBuilder) Build

func (b *EndpointBuilder) Build(apiHandlers ...APIHandler) ApiGroup

Build 构建一个API组

func (*EndpointBuilder) DELETE

func (b *EndpointBuilder) DELETE(path string, handler interface{}, options ...EndpointOption) APIHandler

DELETE 创建一个DELETE方法的端点

func (*EndpointBuilder) GET

func (b *EndpointBuilder) GET(path string, handler interface{}, options ...EndpointOption) APIHandler

GET 创建一个GET方法的端点

func (*EndpointBuilder) GROUP

func (b *EndpointBuilder) GROUP(path string, handlers []APIHandler, options ...GroupOption) APIHandler

func (*EndpointBuilder) HEAD

func (b *EndpointBuilder) HEAD(path string, handler interface{}, options ...EndpointOption) APIHandler

HEAD 创建一个HEAD方法的端点

func (*EndpointBuilder) OPTIONS

func (b *EndpointBuilder) OPTIONS(path string, handler interface{}, options ...EndpointOption) APIHandler

OPTIONS 创建一个OPTIONS方法的端点

func (*EndpointBuilder) PATCH

func (b *EndpointBuilder) PATCH(path string, handler interface{}, options ...EndpointOption) APIHandler

PATCH 创建一个PATCH方法的端点

func (*EndpointBuilder) POST

func (b *EndpointBuilder) POST(path string, handler interface{}, options ...EndpointOption) APIHandler

POST 创建一个POST方法的端点

func (*EndpointBuilder) PUT

func (b *EndpointBuilder) PUT(path string, handler interface{}, options ...EndpointOption) APIHandler

PUT 创建一个PUT方法的端点

type EndpointOption

type EndpointOption func(*ApiEndpoint)

EndpointOption 用于配置端点的可选参数

func WithDescription

func WithDescription(description string) EndpointOption

WithDescription 设置端点描述

func WithMiddleware

func WithMiddleware(middleware ...gin.HandlerFunc) EndpointOption

WithMiddleware 设置端点中间件

func WithSummary

func WithSummary(summary string) EndpointOption

WithSummary 设置端点摘要

func WithTags

func WithTags(tags ...string) EndpointOption

WithTags 设置端点标签

type Error

type Error struct {
	Code    int      // Read-only: error code
	Details []string // Read-only: detailed context
	Status  int      // Read-only: HTTP status
}

---------- 错误结构 ----------

func NewError

func NewError(code int, status ...int) *Error

---------- 工厂函数 ----------

func WrapError

func WrapError(err error, code int, status ...int) *Error

func (*Error) Error

func (e *Error) Error() string

Error implements error interface. For logging only, no i18n.

func (*Error) Log

func (e *Error) Log() *Error

Log logs the error at INFO level

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON output (used in c.JSON)

func (*Error) Msg

func (e *Error) Msg(lang string) string

Msg returns message in specified language (e.g. "zh", "en")

func (*Error) Response

func (e *Error) Response(lang string) any

Response returns a serializable map for HTTP response

func (*Error) WithDetail

func (e *Error) WithDetail(details string) *Error

WithDetail returns a new Error with detail

func (*Error) WithDetailf

func (e *Error) WithDetailf(format string, a ...any) *Error

WithDetailf returns a new Error with formatted detail

type GroupOption

type GroupOption func(*ApiGroup)

func WithGroupDescription

func WithGroupDescription(description string) GroupOption

func WithGroupMiddleware

func WithGroupMiddleware(middleware ...gin.HandlerFunc) GroupOption

func WithGroupTags

func WithGroupTags(tags ...string) GroupOption

type PageData

type PageData struct {
	Data  any `json:"data"`
	Page  int `json:"page"`
	Size  int `json:"size"`
	Total int `json:"total"`
}

type RegistResult

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

func (*RegistResult) Merge

func (r *RegistResult) Merge(other *RegistResult) *RegistResult

type RouterGroup

type RouterGroup interface {
	Group() ApiGroup
}

type Rsp

type Rsp struct {
	Code  int    `json:"code"`
	Msg   string `json:"msg"`
	Page  *int   `json:"page,omitempty"`
	Size  *int   `json:"size,omitempty"`
	Total *int   `json:"total,omitempty"`
	Data  any    `json:"data,omitempty"`
}

type ServeFileSystem

type ServeFileSystem interface {
	http.FileSystem
	Exists(prefix string, path string) bool
}

func EmbedFolder

func EmbedFolder(fsEmbed embed.FS, targetPath string) ServeFileSystem

type Server

type Server struct {
	Engine *gin.Engine
	Config *Config
	// PathPrefixFilter 存储需要保护的API路径前缀
	PathPrefixFilter map[string]bool
	ApiGroups        []ApiGroup
	// contains filtered or unexported fields
}

==================== Server 结构体 ====================

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer 创建 Server

func (*Server) AddPathPrefix

func (s *Server) AddPathPrefix(prefix string)

AddPathPrefix 添加需要保护的API路径前缀 当使用WithEmbeddedFiles注册根路径时,这些前缀将不会被静态文件处理器处理

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

==================== 启动与关闭 ====================

type ServerOption

type ServerOption func(*Server)

func AddApiGroup

func AddApiGroup(group ...ApiGroup) ServerOption

func AddRouteGroup

func AddRouteGroup(prefix string, routes func(*gin.RouterGroup)) ServerOption

AddRouteGroup 添加路由分组

func WithAutoRegister

func WithAutoRegister() ServerOption

WithAutoRegister 自动注册路由

func WithBasePath

func WithBasePath(basePath ...string) ServerOption

func WithCORS

func WithCORS(allowOrigins ...string) ServerOption

WithCORS 启用跨域

func WithEmbeddedFiles

func WithEmbeddedFiles(urlPath string, embeddedFS embed.FS, fsRoot string) ServerOption

WithEmbeddedFiles 提供内嵌静态文件服务 使用方法: //go:embed assets/* var assets embed.FS server := cygin.NewServer(cygin.WithEmbeddedFiles("/assets", assets, "assets"))

func WithHealthCheck

func WithHealthCheck() ServerOption

WithHealthCheck 健康检查

func WithMode

func WithMode(mode string) ServerOption

==================== Gin Mode 控制 ====================

func WithPProf

func WithPProf() ServerOption

WithPProf 启用 pprof 性能分析(仅开发环境建议开启)

func WithPort

func WithPort(port int) ServerOption

WithPort 设置端口

func WithStaticFiles

func WithStaticFiles(urlPath, dirPath string) ServerOption

WithStaticFiles 提供静态文件服务

func WithSwagger

func WithSwagger(swaggerOption ...cyswag.RegisterOption) ServerOption

WithSwagger 启用 Swagger 文档

func WithVersionInfo

func WithVersionInfo() ServerOption

WithVersionInfo 版本信息

type StaticFileConfig

type StaticFileConfig struct {
	UrlPath string
	DirPath string
}

Jump to

Keyboard shortcuts

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