cygin

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// 通用系统错误 (001YYY)
	ErrInternalServer    = 1001 // 内部服务器错误
	ErrDatabaseOperation = 1002 // 数据库操作错误
	ErrUnauthorized      = 1004 // 未授权
	ErrForbidden         = 1005 // 禁止访问
	ErrNotFound          = 1006 // 资源未找到
	ErrTimeout           = 1007 // 操作超时
	ErrParamsInvalid     = 1011 // 参数无效
	ErrBadRequest        = 1012 // 请求错误
)
View Source
const (
	LangEN = "en"
	LangZH = "zh"
)

支持的语言

View Source
const INDEX = "index.html"

Variables

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

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

View Source
var SkipAutoPrivPaths sync.Map

SkipAutoPrivPaths 注册时由 SkipAutoPrivilege=true 的端点自动填充, 供 autoPrivilege 中间件按完整路径跳过 L1 特权注入

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 CompressionLevel added in v1.0.0

func CompressionLevel(level int) string

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 FromCtx

func FromCtx(c *gin.Context) string

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

func GetValidator

func GetValidator() *validator.Validate

GetValidator 返回全局验证器实例

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 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 NewError

func NewError(code int, opts ...ErrorOption) error

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 ResponseError added in v1.0.0

func ResponseError(c *gin.Context, err error)

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 SetupValidator

func SetupValidator()

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

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 ValidateStruct

func ValidateStruct(obj any) error

ValidateStruct 验证结构体

func ValidateStructWithLang

func ValidateStructWithLang(obj any, lang string) error

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

func WrapError

func WrapError(err error, code int, opts ...ErrorOption) error

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 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 CacheableFileSystem added in v1.0.0

type CacheableFileSystem interface {
	ServeFileSystem
	// ClearCache 清空所有缓存
	ClearCache()
	// GetCacheCount 获取缓存条目数
	GetCacheCount() int
}

CacheableFileSystem 支持缓存管理的文件系统接口

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
	Middlewares []gin.HandlerFunc
}

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) 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, 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 设置端点中间件

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
	Silent  bool     // Read-only: whether to silence the error
	Status  int      // Read-only: HTTP status
	// contains filtered or unexported fields
}

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

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

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 ErrorCfg added in v1.0.0

type ErrorCfg struct {
	Status   int
	Details  []string
	PrintLog bool
	Silent   bool
}

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

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 ObjectStoreFileConfig struct {
	UrlPath     string
	Store       *cystore.Store
	Bucket      string
	RootPrefix  string
	Middlewares []gin.HandlerFunc
}

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 ServeMode added in v1.0.0

type ServeMode int

ServeMode 定义 Serve 的工作模式

const (
	ServeModeDefault   ServeMode = iota // 默认模式:处理请求并响应
	ServeModeCheckOnly                  // 仅检查模式:检查文件是否存在,不响应
)

type ServeOptions added in v1.0.0

type ServeOptions struct {
	Mode       ServeMode              // 工作模式
	PathFilter func(path string) bool // 路径过滤器
}

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

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, 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 WithHealthCheck

func WithHealthCheck() ServerOption

WithHealthCheck 健康检查

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 WithPProf

func WithPProf() ServerOption

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

func WithPort

func WithPort(port int) ServerOption

WithPort 设置端口

func WithStaticFiles

func WithStaticFiles(urlPath, dirPath string, opts ...StaticFileOption) 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
	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 返回统一文件服务中间件

Directories

Path Synopsis
Package cyserv provides configuration service functionality with caching support.
Package cyserv provides configuration service functionality with caching support.

Jump to

Keyboard shortcuts

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