第 8 章 模块
8.1 内置模块
内置模块随主程序编译,配置位于 modules.<模块名> 或 location 顶层键。按用途大致分类:
| 类别 | 模块 |
|---|---|
| HTTP 核心 | http_staticfile、http_proxy、http_rewrite、http_headers、http_accesslog |
| 协议客户端 | http_fastcgi、http_uwsgi、http_scgi、http_grpc、http_memcached |
| 安全 | http_waf、http_access、http_auth_basic、http_auth_request、http_auth_jwt、http_secure_link、http_security_headers、http_limit、http_error_guard |
| 过滤与压缩 | http_gzip、http_gunzip、http_brotli、http_zstd、http_sub、http_addition、http_ssi、http_charset、http_minify、http_concat |
| 媒体与内容 | http_image_thumb、http_mp4、http_empty_gif、http_stub_status、http_nchan、http_upload |
| 变量与分流 | http_map、http_geo、http_geoip、http_split_clients、http_realip、http_userid、http_browser、http_referer |
| 可观测与保护 | http_otel、http_logsink、http_mirror、http_sysguard |
模块在 GET /api/modules 与管理后台「模块管理」页列出名称、版本、说明与加载状态。
8.2 外置动态模块
外置模块为原生动态库(cdylib):Linux/FreeBSD 为 .so、macOS 为 .dylib、Windows 为 .dll,通过稳定的 C ABI v2 加载——模块导出 wxserver_module_v2 符号(manifest JSON + on_hook 回调),按需另导出 wxserver_body_filter_v1(流式响应体过滤)与 wxserver_action_v1(管理台动作)。
用任意 Rust crate 构建为 cdylib:
cargo build --release --manifest-path /path/to/plugin/Cargo.toml
# 产物: target/release/lib<name>.so / .dylib / .dll
在配置中启用并传入模块全局配置(按 manifest 的 config schema 校验):
external_modules = [{ path = "/usr/share/wxserver/modules/libexample.so", enabled = true }]
modules = { example = { greeting = "hi" } }
manifest 声明模块实现的钩子、开启条件、配置 schema 与管理台表单/词条;宿主统一校验 manifest、依赖(depends,必选缺失启动失败)与 scope 配置。可选 sha256 哈希固定与 signature/signature_key Ed25519 签名校验(plugin_trust.keys 配置公钥)。增删模块经配置重载生效;示例插件见源码树 plugins/example_echo/。C ABI 细节见 docs/plugin-abi-c.md。
8.3 模块开发接口
内置模块位于 modules/<name>/ 子 crate,用 modules/common 的辅助声明 manifest 并实现对应阶段的 hook trait,经 register_entry! 自注册(linkme 分布式切片)。外置模块通过 C ABI 实现同一 manifest 模型。
按阶段划分的调用方式:
| 阶段 | trait / 机制 | 典型用途 |
|---|---|---|
| Rewrite | BuiltinHandler / AsyncBuiltinHandler |
改写路径、重定向 |
| PreAccess / Access | 同上 | 限流、鉴权、IP 控制 |
| Content | ContentBuiltin(按 location.type 分发) |
代理、FastCGI、静态文件 |
| HeaderFilter | BuiltinHandler |
响应头过滤 |
| BodyFilter | BuiltinHandler / AsyncBodyBuiltin / 外置 wxserver_body_filter_v1 |
压缩、替换、SSI |
| Log | BuiltinHandler(带 LogMeta) |
访问日志 |
| WAF | Phase::WafRequest/WafResponse | 拦截(返回 blocked) |
| service | ServiceBuiltin(plugin::start_services 启动) |
metrics/otel/stream/mail |
阶段顺序固定为 Rewrite → PreAccess → Access → Content → HeaderFilter → BodyFilter → Log。hook 可声明 conditions(methods/path/host/header/cookie/status/tls/cidr)与 priority;HookOutcome 为 Continue / Handled(Resp) / InternalRedirect。完整设计见 docs/plugin-architecture.md,实现状态见 docs/plugin-architecture.md。
8.4 模块禁用
内置模块可以在不重新编译的情况下禁用:
http = {
disabled_modules = ["http_waf", "http_zstd"],
servers = [{ disabled_modules = ["http_image_thumb"] }],
}
被禁用的模块不再执行对应阶段和 content 处理器。禁用 content 模块前,必须移除所有引用它的 location.type,否则 wxserver -t 与管理后台保存都会校验失败。运行时禁用不会强制释放模块已初始化的资源;需要彻底回收请重启进程。必选依赖被禁用时启动失败,可选依赖仅告警。