Documentation
¶
Index ¶
- Constants
- Variables
- func BindAll(c *gin.Context, obj any, bindType BindType) error
- func BindAndValidate(c *gin.Context, obj interface{}) error
- func BindJSONAndValidate(c *gin.Context, obj interface{}) error
- func BindQueryAndValidate(c *gin.Context, obj interface{}) error
- func CompressionLevel(level int) string
- func FromCtx(c *gin.Context) string
- func GetValidator() *validator.Validate
- func Gzip() gin.HandlerFunc
- func Handle[Req any, Rsp any](fn func(c *gin.Context, req Req) (Rsp, error), cb ...cbZeroIO) gin.HandlerFunc
- func HandleAny(fn any, cb ...cbZeroIO) (gin.HandlerFunc, error)
- func HandleNoResp[Req any](fn func(c *gin.Context, req Req, cb ...cbZeroIO) error) gin.HandlerFunc
- func LocalFile(root string, indexes bool) *localFileSystem
- func NewError(code int, opts ...ErrorOption) error
- func RegErrMsg(code int, fn func(lang string) string)
- func RegErrMsgStatic(code int, kvs ...string)
- func RegisterMessages(msgs map[int]map[string]string)
- func ResponseError(c *gin.Context, err error)
- func SecurityHeaders() gin.HandlerFunc
- func Serve(urlPrefix string, fs ServeFileSystem, isGroupPath ...funcIsGroupPath) gin.HandlerFunc
- func ServeWithOption(urlPrefix string, fs ServeFileSystem, options *ServeOptions) gin.HandlerFunc
- func SetDefaultSuccessCode(code int)
- func SetupValidator()
- func StaticCache(maxAge int) gin.HandlerFunc
- func StaticCacheByPath(indexMaxAge, staticMaxAge int) gin.HandlerFunc
- func StaticCacheWithETag(maxAge int, enableETag bool) gin.HandlerFunc
- func ValidateStruct(obj any) error
- func ValidateStructWithLang(obj any, lang string) error
- func WrapError(err error, code int, opts ...ErrorOption) error
- type APIHandler
- type ApiEndpoint
- type ApiGroup
- type ApiMethod
- type BindType
- type CacheableFileSystem
- type Config
- type EmbeddedFileConfig
- type EmbeddedFileOption
- type EmbeddedFileService
- type Endpoint
- type EndpointBuilder
- func (b *EndpointBuilder) ANY(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) Build(apiHandlers ...APIHandler) ApiGroup
- func (b *EndpointBuilder) DELETE(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) GET(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) GROUP(path string, handlers []APIHandler, options ...GroupOption) APIHandler
- func (b *EndpointBuilder) HEAD(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) OPTIONS(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) PATCH(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) POST(path string, handler interface{}, options ...EndpointOption) APIHandler
- func (b *EndpointBuilder) PUT(path string, handler interface{}, options ...EndpointOption) APIHandler
- type EndpointOption
- type Error
- type ErrorCfg
- type ErrorOption
- type FileService
- type FileServiceConfig
- type GroupOption
- type ObjectStoreCacheOption
- type ObjectStoreFileConfig
- type ObjectStoreFileOption
- type ObjectStoreFileService
- func (ofs *ObjectStoreFileService) Exists(path string) (string, bool)
- func (ofs *ObjectStoreFileService) GetMiddlewares() []gin.HandlerFunc
- func (ofs *ObjectStoreFileService) GetURLPath() string
- func (ofs *ObjectStoreFileService) Match(path string) bool
- func (ofs *ObjectStoreFileService) Serve(c *gin.Context)
- type PageInfo
- type PageResult
- type PaginatedResult
- type RegistResult
- type RouterGroup
- type Rsp
- type ServeFileSystem
- type ServeMode
- type ServeOptions
- type Server
- type ServerOption
- func AddApiGroup(group ...ApiGroup) ServerOption
- func AddRouteGroup(prefix string, routes func(*gin.RouterGroup)) ServerOption
- func WithAutoRegister() ServerOption
- func WithBasePath(basePath ...string) ServerOption
- func WithCORS(allowOrigins ...string) ServerOption
- func WithEmbeddedFiles(urlPath string, embeddedFS embed.FS, fsRoot string, opts ...EmbeddedFileOption) ServerOption
- func WithGlobalMiddlewares(middlewares ...gin.HandlerFunc) ServerOption
- func WithHealthCheck() ServerOption
- func WithMode(mode string) ServerOption
- func WithObjectStoreFiles(urlPath string, store *cystore.Store, bucket, rootPrefix string, ...) ServerOption
- func WithPProf() ServerOption
- func WithPort(port int) ServerOption
- func WithStaticFiles(urlPath, dirPath string, opts ...StaticFileOption) ServerOption
- func WithSwagger(swaggerOption ...cyswag.RegisterOption) ServerOption
- func WithVersionInfo() ServerOption
- type StaticFileConfig
- type StaticFileOption
- type StaticFileService
- type UnifiedFileServer
- func (ufs *UnifiedFileServer) AddPathPrefix(prefix string)
- func (ufs *UnifiedFileServer) AddService(service FileService)
- func (ufs *UnifiedFileServer) GetServiceByURL(urlPath string) FileService
- func (ufs *UnifiedFileServer) GetServices() []FileService
- func (ufs *UnifiedFileServer) Middleware() gin.HandlerFunc
Constants ¶
const ( // 通用系统错误 (001YYY) ErrInternalServer = 1001 // 内部服务器错误 ErrDatabaseOperation = 1002 // 数据库操作错误 ErrForbidden = 1005 // 禁止访问 ErrNotFound = 1006 // 资源未找到 ErrTimeout = 1007 // 操作超时 ErrParamsInvalid = 1011 // 参数无效 ErrBadRequest = 1012 // 请求错误 )
const ( LangEN = "en" LangZH = "zh" )
支持的语言
const INDEX = "index.html"
Variables ¶
var ( BuildVersion = "dev" BuildTime = "unknown" )
==================== 全局变量(用于注入版本)====================
var SkipAutoPrivPaths sync.Map
SkipAutoPrivPaths 注册时由 SkipAutoPrivilege=true 的端点自动填充, 供 autoPrivilege 中间件按完整路径跳过 L1 特权注入
Functions ¶
func BindAndValidate ¶
BindAndValidate 绑定请求并验证
func BindJSONAndValidate ¶
BindJSONAndValidate 绑定 JSON 并验证
func BindQueryAndValidate ¶
BindQueryAndValidate 绑定查询参数并验证
func CompressionLevel ¶ added in v1.0.0
GzipWithLevel 启用 Gzip 压缩中间件,指定压缩级别
参数说明:
- level: 压缩级别(1-9)
- 1 = 最快速度,压缩率最低
- 6 = 默认平衡
- 9 = 最高压缩率,速度最慢
使用示例:
server := cygin.NewServer(
cygin.WithStaticFiles(
"/static",
"./web/dist",
cygin.WithStaticMiddlewares(
GzipWithLevel(9), // 最高压缩率
StaticCache(31536000),
),
),
)
特点:
- 支持自定义压缩级别
- 可根据服务器性能和带宽需求调整
局限:
- 压缩级别越高,CPU 消耗越大
- 需要客户端支持 Gzip 解压
注意:
- gzip.DefaultCompression = 6
- gzip.BestSpeed = 1
- gzip.BestCompression = 9
func Gzip ¶ added in v1.0.0
func Gzip() gin.HandlerFunc
Gzip 启用 Gzip 压缩中间件(默认压缩级别) 无需单独 import "github.com/gin-contrib/gzip",直接在 cygin 中使用
使用示例:
server := cygin.NewServer(
cygin.WithStaticFiles(
"/static",
"./web/dist",
cygin.WithStaticMiddlewares(
Gzip(), // 默认压缩级别
StaticCache(31536000),
),
),
)
特点:
- 使用默认压缩级别(6),平衡速度和压缩率
- 无需额外 import
- 自动对响应进行 Gzip 压缩
func Handle ¶
func Handle[ Req any, Rsp any, ](fn func(c *gin.Context, req Req) (Rsp, error), cb ...cbZeroIO) gin.HandlerFunc
通用版本:可返回数据
func HandleNoResp ¶
func NewError ¶
func NewError(code int, opts ...ErrorOption) error
func RegErrMsgStatic ¶
RegErrMsgStatic registers static messages for multiple languages Usage: RegErrMsgStatic(10001, "zh", "用户不存在", "en", "User not found")
func RegisterMessages ¶
RegisterMessages registers multiple error codes at once Usage:
cygin.RegisterMessages(map[int]map[string]string{
10001: {"zh": "登录失败", "en": "Login failed"},
})
func ResponseError ¶ added in v1.0.0
ResponseError sends error response
func SecurityHeaders ¶ added in v1.0.0
func SecurityHeaders() gin.HandlerFunc
SecurityHeaders 添加安全相关的响应头 包括 X-Content-Type-Options、X-Frame-Options、X-XSS-Protection 等
使用示例:
server := cygin.NewServer(
cygin.WithStaticFiles(
"/static",
"./web/dist",
cygin.WithStaticMiddlewares(
SecurityHeaders(),
StaticCache(31536000),
),
),
)
特点:
- 防止 MIME 类型嗅探攻击
- 防止点击劫持
- 防止 XSS 攻击
- 启用 HSTS(可选)
局限:
- 某些旧浏览器可能不支持这些安全头
func Serve ¶
func Serve(urlPrefix string, fs ServeFileSystem, isGroupPath ...funcIsGroupPath) gin.HandlerFunc
Serve 原有的 Serve 函数(保持向后兼容)
func ServeWithOption ¶ added in v1.0.0
func ServeWithOption(urlPrefix string, fs ServeFileSystem, options *ServeOptions) gin.HandlerFunc
ServeWithOption 带选项的 Serve 函数
func SetDefaultSuccessCode ¶
func SetDefaultSuccessCode(code int)
func StaticCache ¶ added in v1.0.0
func StaticCache(maxAge int) gin.HandlerFunc
StaticCache 为静态资源设置缓存策略中间件 在响应头中添加 Cache-Control 字段,用于控制浏览器和 CDN 的缓存行为
参数说明:
- maxAge: 缓存时间(秒)
- 31536000 = 1 年(适合带 hash 的静态资源)
- 86400 = 1 天
- 3600 = 1 小时
- 0 = 不缓存
使用示例:
server := cygin.NewServer(
cygin.WithStaticFiles(
"/static",
"./web/dist",
cygin.WithStaticMiddlewares(
StaticCache(31536000), // 1 年缓存
),
),
)
特点:
- 使用 public 策略,允许浏览器和 CDN 缓存
- 可与 Gzip 中间件组合使用
- 对所有静态文件统一应用相同的缓存策略
局限:
- 如果需要对不同文件类型设置不同的缓存时间,需要在此基础上扩展
- 不支持 ETag 或 Last-Modified 的条件请求优化
func StaticCacheByPath ¶ added in v1.0.0
func StaticCacheByPath(indexMaxAge, staticMaxAge int) gin.HandlerFunc
StaticCacheByPath 根据文件路径设置不同的缓存策略 适用于需要对不同类型文件设置不同缓存时间的场景
参数说明:
- indexMaxAge: index.html 的缓存时间(秒),通常设置较短(如 3600)
- staticMaxAge: 其他静态资源的缓存时间(秒),通常设置较长(如 31536000)
使用示例:
server := cygin.NewServer(
cygin.WithStaticFiles(
"/static",
"./web/dist",
cygin.WithStaticMiddlewares(
StaticCacheByPath(3600, 31536000), // index.html 1小时,其他资源 1年
),
),
)
特点:
- 对 index.html 使用较短的缓存时间,确保能及时更新
- 对带 hash 的资源文件使用较长的缓存时间,提高性能
- 适合 SPA 应用的缓存策略
局限:
- 只支持两种缓存策略,如需更细粒度的控制,需要进一步扩展
func StaticCacheWithETag ¶ added in v1.0.0
func StaticCacheWithETag(maxAge int, enableETag bool) gin.HandlerFunc
StaticCacheWithETag 为静态资源设置缓存策略,并支持 ETag 验证 相比 StaticCache,额外支持浏览器的 304 Not Modified 优化
参数说明:
- maxAge: 缓存时间(秒)
- enableETag: 是否启用 ETag 验证
使用示例:
server := cygin.NewServer(
cygin.WithStaticFiles(
"/static",
"./web/dist",
cygin.WithStaticMiddlewares(
StaticCacheWithETag(31536000, true),
),
),
)
特点:
- 支持 ETag 验证,减少不必要的文件传输
- 浏览器可以通过 If-None-Match 请求验证文件是否更新
- 返回 304 Not Modified 时无需传输文件内容
局限:
- ETag 计算会增加一定的 CPU 开销
- 对于大文件,ETag 计算可能较慢
func ValidateStructWithLang ¶
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
// SkipAutoPrivilege 标记该端点不需要 L1 自动特权注入(如公开 API、健康检查等)
SkipAutoPrivilege bool
}
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
IgnoreBasePath bool // 如果为 true,则忽略 WithBasePath 设置的全局 basePath
}
func (*ApiGroup) RegistRouter ¶
func (ag *ApiGroup) RegistRouter(basePath string, g *gin.RouterGroup) *RegistResult
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 CacheableFileSystem ¶ added in v1.0.0
type CacheableFileSystem interface {
ServeFileSystem
// ClearCache 清空所有缓存
ClearCache()
// GetCacheCount 获取缓存条目数
GetCacheCount() int
}
CacheableFileSystem 支持缓存管理的文件系统接口
type EmbeddedFileConfig ¶
type EmbeddedFileOption ¶ added in v1.0.0
type EmbeddedFileOption func(*EmbeddedFileConfig)
func WithEmbeddedMiddlewares ¶ added in v1.0.0
func WithEmbeddedMiddlewares(middlewares ...gin.HandlerFunc) EmbeddedFileOption
WithEmbeddedMiddlewares 为嵌入式文件路由附加中间件(例如 gzip、缓存头等)
type EmbeddedFileService ¶ added in v1.0.0
type EmbeddedFileService struct {
FileServiceConfig
FS embed.FS
Root string
// contains filtered or unexported fields
}
EmbeddedFileService 嵌入式文件服务
func NewEmbeddedFileService ¶ added in v1.0.0
func NewEmbeddedFileService(urlPath string, filesystem embed.FS, root string, middlewares ...gin.HandlerFunc) *EmbeddedFileService
NewEmbeddedFileService 创建嵌入式文件服务
func (*EmbeddedFileService) Exists ¶ added in v1.0.0
func (efs *EmbeddedFileService) Exists(path string) (string, bool)
func (*EmbeddedFileService) GetMiddlewares ¶ added in v1.0.0
func (efs *EmbeddedFileService) GetMiddlewares() []gin.HandlerFunc
func (*EmbeddedFileService) GetURLPath ¶ added in v1.0.0
func (efs *EmbeddedFileService) GetURLPath() string
func (*EmbeddedFileService) Match ¶ added in v1.0.0
func (efs *EmbeddedFileService) Match(path string) bool
func (*EmbeddedFileService) Serve ¶ added in v1.0.0
func (efs *EmbeddedFileService) Serve(c *gin.Context)
type Endpoint ¶
type Endpoint struct {
// contains filtered or unexported fields
}
Endpoint 创建一个基础端点
func (Endpoint) WithDescription ¶
WithDescription 设置端点描述
func (Endpoint) WithSummary ¶
WithSummary 设置端点摘要
type EndpointBuilder ¶
type EndpointBuilder struct {
// contains filtered or unexported fields
}
EndpointBuilder 是一个用于构建 API 端点的辅助函数集合
func NewEndpointBuilder ¶
func NewEndpointBuilder(basePath string, description string, tags []string, ignoreBasePath ...bool) *EndpointBuilder
NewEndpointBuilder 创建一个新的端点构建器 ignoreBasePath: 可选参数,如果为 true,则忽略 WithBasePath 设置的全局 basePath
func (*EndpointBuilder) ANY ¶ added in v1.0.0
func (b *EndpointBuilder) ANY(path string, handler interface{}, options ...EndpointOption) APIHandler
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 设置端点中间件
type Error ¶
type Error struct {
Code int // Read-only: error code
Details []string // Read-only: detailed context
Silent bool // Read-only: whether to silence the error
Status int // Read-only: HTTP status
// contains filtered or unexported fields
}
---------- 错误结构 ----------
func (*Error) MarshalJSON ¶
MarshalJSON customizes JSON output (used in c.JSON)
func (*Error) WithDetail ¶
WithDetail returns a new Error with detail
type ErrorOption ¶ added in v1.0.0
type ErrorOption func(cfg *ErrorCfg)
func WithErrDetailf ¶ added in v1.0.0
func WithErrDetailf(format string, a ...any) ErrorOption
func WithErrDetails ¶ added in v1.0.0
func WithErrDetails(details ...string) ErrorOption
func WithErrPrint ¶ added in v1.0.0
func WithErrPrint() ErrorOption
func WithErrSilent ¶ added in v1.0.0
func WithErrSilent(silent bool) ErrorOption
func WithStatus ¶ added in v1.0.0
func WithStatus(status int) ErrorOption
type FileService ¶ added in v1.0.0
type FileService interface {
// Match 检查路径是否匹配此服务
Match(path string) bool
// Exists 检查文件是否存在,返回实际存在的路径和是否存在
Exists(path string) (actualPath string, exists bool)
// Serve 处理文件请求
Serve(c *gin.Context)
// GetMiddlewares 获取中间件列表
GetMiddlewares() []gin.HandlerFunc
// GetURLPath 获取 URL 前缀
GetURLPath() string
}
FileService 文件服务接口
type FileServiceConfig ¶ added in v1.0.0
type FileServiceConfig struct {
URLPath string
Middlewares []gin.HandlerFunc
}
FileServiceConfig 文件服务配置
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 ObjectStoreCacheOption ¶ added in v1.0.0
type ObjectStoreCacheOption func(*objectStoreFileSystem)
ObjectStoreCacheOption 对象存储文件系统缓存的选项函数
func WithCacheTTL ¶ added in v1.0.0
func WithCacheTTL(ttl time.Duration) ObjectStoreCacheOption
WithCacheTTL 设置缓存过期时间 参数说明:
- ttl: 缓存过期时间,0 表示永不过期
使用示例:
fs := ObjectStoreFile(store, "my-bucket", "web/assets/",
WithCacheTTL(1*time.Hour), // 1 小时过期
)
func WithDebug ¶ added in v1.0.0
func WithDebug(enabled bool) ObjectStoreCacheOption
WithDebug 启用调试模式,打印详细的日志信息 参数说明:
- enabled: 是否启用调试模式,默认 false
使用示例:
fs := ObjectStoreFile(store, "my-bucket", "web/assets/",
WithDebug(true), // 启用调试日志
)
调试日志会输出文件访问、路径解析等详细信息,用于排查问题
func WithMaxCacheSize ¶ added in v1.0.0
func WithMaxCacheSize(maxSize int64) ObjectStoreCacheOption
WithMaxCacheSize 设置最大缓存大小 参数说明:
- maxSize: 最大缓存大小(字节),0 表示无限制
使用示例:
fs := ObjectStoreFile(store, "my-bucket", "web/assets/",
WithMaxCacheSize(100*1024*1024), // 100 MB
)
当缓存超过限制时,会自动清理最少使用的文件(LRU)
type ObjectStoreFileConfig ¶ added in v1.0.0
type ObjectStoreFileOption ¶ added in v1.0.0
type ObjectStoreFileOption func(*ObjectStoreFileConfig)
func WithObjectStoreMiddlewares ¶ added in v1.0.0
func WithObjectStoreMiddlewares(middlewares ...gin.HandlerFunc) ObjectStoreFileOption
WithObjectStoreMiddlewares 为对象存储文件路由附加中间件
type ObjectStoreFileService ¶ added in v1.0.0
type ObjectStoreFileService struct {
FileServiceConfig
Store *cystore.Store
Bucket string
RootPrefix string
// contains filtered or unexported fields
}
ObjectStoreFileService 对象存储文件服务
func NewObjectStoreFileService ¶ added in v1.0.0
func NewObjectStoreFileService(urlPath string, store *cystore.Store, bucket string, rootPrefix string, middlewares ...gin.HandlerFunc) *ObjectStoreFileService
NewObjectStoreFileService 创建对象存储文件服务
func (*ObjectStoreFileService) Exists ¶ added in v1.0.0
func (ofs *ObjectStoreFileService) Exists(path string) (string, bool)
func (*ObjectStoreFileService) GetMiddlewares ¶ added in v1.0.0
func (ofs *ObjectStoreFileService) GetMiddlewares() []gin.HandlerFunc
func (*ObjectStoreFileService) GetURLPath ¶ added in v1.0.0
func (ofs *ObjectStoreFileService) GetURLPath() string
func (*ObjectStoreFileService) Match ¶ added in v1.0.0
func (ofs *ObjectStoreFileService) Match(path string) bool
func (*ObjectStoreFileService) Serve ¶ added in v1.0.0
func (ofs *ObjectStoreFileService) Serve(c *gin.Context)
type PageInfo ¶ added in v1.0.0
type PageInfo struct {
Page int `json:"page"` // 当前页码
Size int `json:"size"` // 每页大小
TotalCount int64 `json:"totalCount"` // 总记录数
}
PageInfo 分页信息
type PageResult ¶ added in v1.0.0
type PageResult struct {
Data any `json:"data"` // 当前页数据
Page *PageInfo `json:"page,omitempty"` // 分页信息
}
PageResult 分页结果(简化版,分页信息在 Page 字段中)
type PaginatedResult ¶ added in v1.0.0
type PaginatedResult[T any] = cydb.PaginatedResult[T]
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"`
Success bool `json:"success"` // 是否成功(code == 200 时为 true)
Silent *bool `json:"silent,omitempty"` // 是否静默(用于前端错误提示)
CostTime string `json:"costTime,omitempty"` // 请求耗时
Page *PageInfo `json:"page,omitempty"` // 分页信息(仅分页查询时存在)
Data any `json:"data,omitempty"` // 业务数据
HttpStatus *int `json:"-"` // HTTP 状态码
Debug any `json:"debug,omitempty"`
}
type ServeFileSystem ¶
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) (actualPath string, exists bool)
}
func EmbedFolder ¶
func EmbedFolder(fsEmbed embed.FS, targetPath string) ServeFileSystem
func ObjectStoreFile ¶ added in v1.0.0
func ObjectStoreFile(store *cystore.Store, bucket, rootPrefix string, opts ...ObjectStoreCacheOption) ServeFileSystem
ObjectStoreFile 从对象存储提供静态文件服务 使用 cystore 作为存储后端(支持 S3、MinIO、本地存储等) 支持内存缓存,避免重复从对象存储读取文件
参数说明:
- store: cystore.Store 实例,用于访问对象存储
- bucket: 存储桶名称
- rootPrefix: 对象存储中的根路径前缀(可选),例如 "static/" 或 "web/dist/"
- opts: 可选的配置选项(如缓存 TTL)
使用示例:
// 创建 cystore 实例
config := &cystore.Config{
Provider: cystore.ProviderMinio,
Endpoint: "localhost:9000",
AccessKey: "minioadmin",
SecretKey: "minioadmin",
}
store, err := cystore.NewStore(config)
if err != nil {
panic(err)
}
// 注册静态文件服务(带缓存)
server := cygin.NewServer(
cygin.WithObjectStoreFiles(
"/assets",
store,
"my-bucket",
"web/assets/",
cygin.WithObjectStoreMiddlewares(
Gzip(),
StaticCache(31536000),
),
),
)
特点:
- 支持多种对象存储后端(S3、MinIO、本地存储等)
- 自动处理 index.html 回退(SPA 支持)
- 支持自定义根路径前缀
- 支持内存缓存,避免重复请求对象存储
- 支持可配置的缓存过期时间
- 支持与其他中间件组合(gzip、缓存等)
局限:
- 内存缓存会占用服务器内存,大文件较多时需要注意内存使用
- 缓存不会自动更新,需要手动清空或等待过期
- 需要网络连接到对象存储服务(首次读取)
type ServeOptions ¶ added in v1.0.0
ServeOptions Serve 函数的选项
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
func NewServerWithCtx ¶ added in v1.0.0
func NewServerWithCtx(ctx context.Context, opts ...ServerOption) *Server
NewServer 创建 Server
func (*Server) AddPathPrefix ¶
AddPathPrefix 添加需要保护的API路径前缀 当使用WithEmbeddedFiles注册根路径时,这些前缀将不会被静态文件处理器处理
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 WithBasePath ¶
func WithBasePath(basePath ...string) ServerOption
func WithEmbeddedFiles ¶
func WithEmbeddedFiles(urlPath string, embeddedFS embed.FS, fsRoot string, opts ...EmbeddedFileOption) ServerOption
WithEmbeddedFiles 提供内嵌静态文件服务 使用方法: //go:embed assets/* var assets embed.FS server := cygin.NewServer(cygin.WithEmbeddedFiles("/assets", assets, "assets"))
func WithGlobalMiddlewares ¶ added in v1.0.0
func WithGlobalMiddlewares(middlewares ...gin.HandlerFunc) ServerOption
WithGlobalMiddlewares 添加全局中间件
func WithMode ¶
func WithMode(mode string) ServerOption
==================== Gin Mode 控制 ====================
func WithObjectStoreFiles ¶ added in v1.0.0
func WithObjectStoreFiles(urlPath string, store *cystore.Store, bucket, rootPrefix string, opts ...ObjectStoreFileOption) ServerOption
WithObjectStoreFiles 从对象存储(S3、MinIO 等)提供静态文件服务 使用 cystore 作为存储后端
参数说明:
- urlPath: URL 路径前缀,例如 "/assets"
- store: cystore.Store 实例
- bucket: 存储桶名称
- rootPrefix: 对象存储中的根路径前缀,例如 "web/assets/" 或 "static/"
- opts: 可选的中间件配置
使用示例:
config := &cystore.Config{
Provider: cystore.ProviderMinio,
Endpoint: "localhost:9000",
AccessKey: "minioadmin",
SecretKey: "minioadmin",
}
store, err := cystore.NewStore(config)
if err != nil {
panic(err)
}
server := cygin.NewServer(
cygin.WithObjectStoreFiles(
"/assets",
store,
"my-bucket",
"web/assets/",
cygin.WithObjectStoreMiddlewares(
Gzip(),
StaticCache(31536000),
),
),
)
func WithStaticFiles ¶
func WithStaticFiles(urlPath, dirPath string, opts ...StaticFileOption) ServerOption
WithStaticFiles 提供静态文件服务
func WithSwagger ¶
func WithSwagger(swaggerOption ...cyswag.RegisterOption) ServerOption
WithSwagger 启用 Swagger 文档
type StaticFileConfig ¶
type StaticFileConfig struct {
UrlPath string
DirPath string
Middlewares []gin.HandlerFunc
}
type StaticFileOption ¶ added in v1.0.0
type StaticFileOption func(*StaticFileConfig)
func WithStaticMiddlewares ¶ added in v1.0.0
func WithStaticMiddlewares(middlewares ...gin.HandlerFunc) StaticFileOption
WithStaticMiddlewares 为静态文件路由附加中间件(例如 gzip、缓存头等)
type StaticFileService ¶ added in v1.0.0
type StaticFileService struct {
FileServiceConfig
DirPath string
// contains filtered or unexported fields
}
StaticFileService 静态文件服务
func NewStaticFileService ¶ added in v1.0.0
func NewStaticFileService(urlPath string, dirPath string, middlewares ...gin.HandlerFunc) *StaticFileService
NewStaticFileService 创建静态文件服务
func (*StaticFileService) Exists ¶ added in v1.0.0
func (sfs *StaticFileService) Exists(path string) (string, bool)
func (*StaticFileService) GetMiddlewares ¶ added in v1.0.0
func (sfs *StaticFileService) GetMiddlewares() []gin.HandlerFunc
func (*StaticFileService) GetURLPath ¶ added in v1.0.0
func (sfs *StaticFileService) GetURLPath() string
func (*StaticFileService) Match ¶ added in v1.0.0
func (sfs *StaticFileService) Match(path string) bool
func (*StaticFileService) Serve ¶ added in v1.0.0
func (sfs *StaticFileService) Serve(c *gin.Context)
type UnifiedFileServer ¶ added in v1.0.0
type UnifiedFileServer struct {
// contains filtered or unexported fields
}
UnifiedFileServer 统一文件服务器
func NewUnifiedFileServer ¶ added in v1.0.0
func NewUnifiedFileServer() *UnifiedFileServer
NewUnifiedFileServer 创建统一文件服务器
func (*UnifiedFileServer) AddPathPrefix ¶ added in v1.0.0
func (ufs *UnifiedFileServer) AddPathPrefix(prefix string)
AddPathPrefix 添加路径前缀过滤器
func (*UnifiedFileServer) AddService ¶ added in v1.0.0
func (ufs *UnifiedFileServer) AddService(service FileService)
AddService 添加文件服务
func (*UnifiedFileServer) GetServiceByURL ¶ added in v1.0.0
func (ufs *UnifiedFileServer) GetServiceByURL(urlPath string) FileService
GetServiceByURL 根据 URL 获取文件服务
func (*UnifiedFileServer) GetServices ¶ added in v1.0.0
func (ufs *UnifiedFileServer) GetServices() []FileService
GetServices 获取所有文件服务
func (*UnifiedFileServer) Middleware ¶ added in v1.0.0
func (ufs *UnifiedFileServer) Middleware() gin.HandlerFunc
Middleware 返回统一文件服务中间件