webiris

package
v1.42.0 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultTimeFormat 是 Web 服务未指定时间格式时使用的默认格式。
	DefaultTimeFormat = "2006-01-02 15:04:05"
	// DefaultLogLevel 是 Iris 框架日志未指定级别时使用的默认级别。
	DefaultLogLevel = "info"
	// DefaultShutdownTimeout 是优雅关闭等待存量 HTTP 请求结束的默认时长。
	DefaultShutdownTimeout = 10 * time.Second
)
View Source
const DefaultAdminListen = ":6060"

DefaultAdminListen 是管理服务默认监听地址。

View Source
const RequestIDHeader = "X-Request-ID"

RequestIDHeader 是 Request ID 透传/写入的响应头名称。

Variables

This section is empty.

Functions

func AccessLog

func AccessLog(ctx iris.Context)

AccessLog 中间件记录方法、路径、状态码、耗时、Request ID 与客户端地址。 用法:app.Use(AccessLog)

func Auth

func Auth(config ...AuthConfig) iris.Handler

Auth 返回 JWT 认证中间件。 校验 Authorization: Bearer <token> 头(使用 apptoken.VerifyToken, 需先通过 apptoken.SetSecretKey 注入密钥);认证通过后把用户身份写入 ctx.Values() 的 user_id / user_email,业务代码通过 UserID / UserEmail 读取。 认证失败返回 401 统一响应;配置 Scope 时无权限返回 403 统一响应。 用法:app.Use(webiris.Auth(webiris.AuthConfig{Whitelist: []string{"/health", "/login"}}))

func BodyLimit added in v1.12.0

func BodyLimit(maxBytes int64) iris.Handler

BodyLimit 返回请求体大小限制中间件(DoS 防护:超大请求体拦截)。 maxBytes 为上限(字节),超限返回 413 A0400。 用法:app.Use(webiris.BodyLimit(1 << 20)) // 1MB

func CORS

func CORS(allowedOrigins ...string) iris.Handler

CORS 中间件添加跨域响应头。 不传 allowedOrigins 时允许所有来源;传入时仅放行匹配来源;OPTIONS 预检直接返回 204。 用法:app.Use(CORS()) 或 app.Use(CORS("https://trusted.example.com"))

func DataScope added in v1.11.0

func DataScope(ctx iris.Context) datasource.DataScope

DataScope 从上下文读取认证用户的数据权限范围(组织/部门)。 与 framework/database 的 DataScope 配套:登录时通过 apptoken.GenTokenFull 写入组织身份,认证后此处取回,查询时直接 Scopes(scope.Condition()) 隔离数据。 未认证或 token 无组织字段时返回空范围(不限制)。

func ErrorHandler

func ErrorHandler(ctx iris.Context)

ErrorHandler 是全局错误处理中间件: 捕获处理器 panic 并输出 500 统一响应,避免框架默认 HTML 错误页。 应注册在所有路由之前:app.Use(webiris.ErrorHandler)。

func Fail

func Fail(ctx iris.Context, httpStatus int, code apperr.Code, message string)

Fail 返回失败响应并设置 HTTP 状态码;code 为手册 A/B/C 业务错误码。

func Limit

func Limit(ratePerSecond float64, burst int, keyFunc func(ctx iris.Context) string) iris.Handler

Limit 返回令牌桶限流中间件。 ratePerSecond 是每秒补充的令牌数;burst 是突发容量(非正数时取 ratePerSecond)。 keyFunc 返回限流维度(如客户端 IP、用户 ID);为 nil 时全局限流。 超限请求返回 429 统一响应并停止后续处理器。 用法:app.Use(webiris.Limit(100, 200, nil)) 或按 IP:app.Use(webiris.Limit(10, 20, func(ctx iris.Context) string { return ctx.RemoteAddr() }))

func OK

func OK(ctx iris.Context, data interface{})

OK 返回成功响应。

func RegisterHealth

func RegisterHealth(app *iris.Application, ready func() error)

RegisterHealth 注册存活与就绪探针端点。 /health/live 始终返回 ok;/health/ready 在 ready 回调返回错误时响应 503。

func RegisterPprof

func RegisterPprof(app *iris.Application)

RegisterPprof 注册 /debug/pprof 诊断端点(heap、goroutine、profile、trace 等)。 生产环境建议通过配置开关决定是否注册。

func RegisterRoutes added in v1.31.0

func RegisterRoutes(app *iris.Application, routeGroups ...[]Route)

RegisterRoutes 批量注册路由(可选附带 apidoc 文档)。 传多个路由切片可组合分组(如 router.OrderRoutes(), router.UserRoutes())。

func RequestID

func RequestID(ctx iris.Context)

RequestID 中间件为每个请求生成或透传 Request ID,并写入响应头与上下文。 透传来源:请求头 X-Request-ID;业务代码可通过 ctx.Values().GetString("request_id") 读取。 用法:app.Use(RequestID)

func RespondError

func RespondError(ctx iris.Context, err error)

RespondError 把错误转为统一响应: apperr.Error 按自身状态码与业务码输出;其他错误输出 500(服务端日志记录原始错误)。

func SQLGuard added in v1.12.0

func SQLGuard() iris.Handler

SQLGuard 返回 SQL 注入防护中间件:检测 query 参数与请求体中的注入特征, 命中返回 400 A0400 并停止处理(建议挂在限流之后、业务路由之前)。 注意:此中间件是前置拦截,不能替代参数化查询。

app.Use(webiris.SQLGuard())

func SecurityHeaders

func SecurityHeaders(ctx iris.Context)

SecurityHeaders 中间件添加基础安全响应头。 用法:app.Use(SecurityHeaders)

func Timeout added in v1.12.0

func Timeout(timeout time.Duration) iris.Handler

Timeout 返回请求超时中间件(DoS 防护:慢速请求拦截)。 超时后返回 504 B0100;业务应配合 context 感知(查询/HTTP 调用带 ctx)。 用法:app.Use(webiris.Timeout(10 * time.Second))

func UserDeptID added in v1.11.0

func UserDeptID(ctx iris.Context) int64

UserDeptID 从上下文读取认证用户的部门 ID;未认证或缺失时返回 0。

func UserEmail

func UserEmail(ctx iris.Context) string

UserEmail 从上下文读取认证用户邮箱;未认证或缺失时返回空字符串。

func UserID

func UserID(ctx iris.Context) int64

UserID 从上下文读取认证用户 ID;未认证或缺失时返回 0。

func UserOrgID added in v1.11.0

func UserOrgID(ctx iris.Context) int64

UserOrgID 从上下文读取认证用户的组织 ID;未认证或缺失时返回 0。

Types

type Admin

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

Admin 是独立监听的管理服务: /debug/pprof/*(诊断)、/metrics(Prometheus 指标)、POST /cl(运行时日志级别)、 以及业务通过 RegisterRoutes 注册的管理路由。 管理端口与业务 Web 端口分离,适合暴露给运维/监控体系。

func NewAdmin

func NewAdmin() *Admin

NewAdmin 创建默认配置的管理服务。

func NewAdminWithConfig

func NewAdminWithConfig(config AdminConfig) *Admin

NewAdminWithConfig 按配置创建管理服务。

func (*Admin) Ready

func (a *Admin) Ready() <-chan struct{}

Ready 返回就绪信号:管理服务真正开始监听后关闭。

func (*Admin) RegisterRoutes

func (a *Admin) RegisterRoutes(register func(app *iris.Application)) *Admin

RegisterRoutes 注册业务管理路由(不会覆盖框架内置 API)。

func (*Admin) Run

func (a *Admin) Run(ctx context.Context) error

Run 启动管理监听并阻塞,直到 Context 取消。 内置 API 先注册,业务路由后注册,业务无法覆盖框架 API。

type AdminConfig

type AdminConfig struct {
	// Listen 是监听地址,空值使用 DefaultAdminListen。
	Listen string
	// EnablePprof 控制 /debug/pprof 诊断端点,默认开启。
	EnablePprof bool
	// EnableMetrics 控制 /metrics Prometheus 端点,默认开启。
	EnableMetrics bool
	// EnableLogLevel 控制 POST /cl 运行时日志级别切换,默认开启。
	EnableLogLevel bool
	// ShutdownTimeout 是优雅关闭超时,默认 5 秒。
	ShutdownTimeout time.Duration
}

AdminConfig 定义管理服务配置。

type AuthConfig

type AuthConfig struct {
	// Whitelist 是无需认证的路径前缀列表(如 /health、/login)。
	// 路径以任一前缀开头时直接放行。
	Whitelist []string
	// Scope 是本接口要求的权限标识(逗号分隔匹配 token 声明的 scope)。
	// 非空时,token 声明未包含该 scope 的请求返回 403。
	Scope string
}

AuthConfig 定义 JWT 认证中间件配置。

type Config

type Config struct {
	Address         string        // Address 是 TCP 监听地址。
	TimeFormat      string        // TimeFormat 控制 Iris 输出时间的格式。
	LogLevel        string        // LogLevel 控制 Iris 框架日志级别。
	ShutdownTimeout time.Duration // ShutdownTimeout 限制优雅关闭的最长等待时间。
}

Config 描述 Iris Web 服务的运行参数。 Address 必须是 host:port 格式,例如 :9528、127.0.0.1:9528 或 [::1]:9528。

type PartyComponent

type PartyComponent func(app *iris.Application)

PartyComponent 用于向 Iris Application 注册路由、中间件和错误处理器。 回调仅在 WebIris 初始化时执行一次,不应在其中启动无退出机制的 goroutine。

type Response

type Response struct {
	Code    apperr.Code `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

Response 是统一业务响应结构。 Code 为业务码(0 表示成功),Message 为可读信息,Data 为负载。

type Route added in v1.31.0

type Route struct {
	Method  string          // HTTP 方法:GET/POST/PUT/DELETE
	Path    string          // 路由路径(支持 iris 参数语法 /{id:int64})
	Handler iris.Handler    // 处理函数
	Doc     []apidoc.Option // 可选:接口文档描述(apidoc.Summary 等);nil 时仅注册路由
}

Route 路由定义(业务项目分组注册用)。 业务项目在内部 router 包定义路由函数返回 Route 切片, main 中一行挂载,避免全部路由堆在 main。

// internal/router/order.go(业务项目,按功能分组)
func OrderRoutes() []webiris.Route {
    return []webiris.Route{
        {Method: "GET", Path: "/api/v1/orders", Handler: handler.ListOrder},
        {Method: "POST", Path: "/api/v1/orders", Handler: handler.CreateOrder,
         Doc: []apidoc.Option{apidoc.Body(&model.Order{}, true, "创建"), apidoc.Responds(&model.Order{})}},
    }
}

// internal/router/router.go(组合分组:一级/二级路由按类型功能组织)
func All() []webiris.Route {
    var routes []webiris.Route
    routes = append(routes, OrderRoutes()...)
    routes = append(routes, UserRoutes()...)
    return routes
}

// main.go(一行挂载)
webiris.RegisterRoutes(app, router.All())

type WebBaseFunc

type WebBaseFunc interface {
	// Run 启动 Web 服务并阻塞到启动失败、运行失败或 Context 被取消。
	Run(ctx context.Context) error
	// StaticSource 在 Web 启动前注册静态文件系统。
	StaticSource(fs http.FileSystem) error
}

WebBaseFunc 是 Application Starter 启动 Web 服务所依赖的最小接口。

type WebIris

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

WebIris 封装 Iris Application、运行配置和生命周期状态。 同一实例只允许运行一次,关闭后需要创建新实例才能再次启动。

func Init

func Init(timeFormat, port, logLevel string, components PartyComponent) *WebIris

Init 保留原有参数式构造 API,供已有依赖项目平滑升级。 无效配置不会被忽略,而是在后续 Run 调用时记录并返回。

func InitWithConfig

func InitWithConfig(config Config, components PartyComponent) *WebIris

InitWithConfig 保留单返回值和链式调用风格。 与 New 不同,该方法把配置错误保存在实例中,由 Run 统一处理。

func New

func New(config Config, components PartyComponent) (*WebIris, error)

New 创建并校验一个 Iris Web 服务。 新代码应优先使用该方法,在应用启动前处理配置错误。

func (*WebIris) Application

func (w *WebIris) Application() *iris.Application

Application 返回底层 Iris Application,供依赖方使用 Iris 原生高级能力。 路由和中间件仍需在 Run 前完成注册。

func (*WebIris) Ready

func (w *WebIris) Ready() <-chan struct{}

Ready 返回只读启动信号。 Iris Host 真正进入 Serve 阶段后该 Channel 会关闭,调用方无需固定 Sleep。

func (*WebIris) Run

func (w *WebIris) Run(ctx context.Context) error

Run 构建路由、监听 TCP 端口并阻塞等待服务退出。 Context 取消后执行限时优雅关闭,启动和关闭错误都会记录日志并返回调用方。

func (*WebIris) StaticSource

func (w *WebIris) StaticSource(fs http.FileSystem) error

StaticSource 将文件系统注册到根路径,用于提供 SPA 或其他静态资源。 该方法必须在 Run 前调用;启动后修改路由会直接返回错误。

Jump to

Keyboard shortcuts

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