Documentation
¶
Overview ¶
Package adaptor 提供 hertz-contrib/adaptor 常用 helper,让 ekit 业务 用 1 行代码把 net/http 生态(http.FileServer / embed.FS / gorilla/websocket)接入 hertz。
官方依据:https://www.cloudwego.io/zh/docs/hertz/tutorials/basic-feature/http-adaptor/ (2025-05-21 新教程)。背景:
- 淘汰长期没有良好维护的 hertz app.FS
- 通过官方 net/http 生态提供兼容性更好、性能也不差的 fs
- 允许在 hertz 用 http.FileServer / embed.FS / gorilla/websocket
设计:ekit 包装 4 个最常见场景,1 行挂载。
Index ¶
- func HertzHandler(h http.Handler) app.HandlerFunc
- func HertzHandlerFunc(h http.HandlerFunc) app.HandlerFunc
- func NativeStaticFSHandler(prefix string, fsys fs.FS, opts ...NativeStaticOption) app.HandlerFunc
- func PerformRequest(e *route.Engine, method, url string, body *ut.Body, headers ...ut.Header) (int, []byte)
- func StaticDirHandler(prefix, dir string) app.HandlerFunc
- func StaticFSHandler(prefix string, efs embed.FS) app.HandlerFunc
- type MockConn
- func (m *MockConn) Close() error
- func (m *MockConn) Flush() error
- func (m *MockConn) Len() int
- func (m *MockConn) LocalAddr() net.Addr
- func (m *MockConn) Malloc(n int) ([]byte, error)
- func (m *MockConn) Out() []byte
- func (m *MockConn) Peek(int) ([]byte, error)
- func (m *MockConn) Read([]byte) (int, error)
- func (m *MockConn) ReadBinary(int) ([]byte, error)
- func (m *MockConn) ReadByte() (byte, error)
- func (m *MockConn) Release() error
- func (m *MockConn) RemoteAddr() net.Addr
- func (m *MockConn) SetDeadline(time.Time) error
- func (m *MockConn) SetReadDeadline(time.Time) error
- func (m *MockConn) SetReadTimeout(time.Duration) error
- func (m *MockConn) SetWriteDeadline(time.Time) error
- func (m *MockConn) SetWriteTimeout(time.Duration) error
- func (m *MockConn) Skip(int) error
- func (m *MockConn) Write(p []byte) (int, error)
- func (m *MockConn) WriteBinary(b []byte) (int, error)
- type NativeStaticOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HertzHandler ¶
func HertzHandler(h http.Handler) app.HandlerFunc
HertzHandler 透传 hertz-contrib adaptor.HertzHandler(http.Handler), 让业务不用记 import 长路径。直接传 hertz 注册用。
官方依据:https://www.cloudwego.io/zh/docs/hertz/tutorials/basic-feature/http-adaptor/ "adaptor.HertzHandler 允许你将现有的 http.HandlerFunc 方法直接转为 HertzHandler"
func HertzHandlerFunc ¶
func HertzHandlerFunc(h http.HandlerFunc) app.HandlerFunc
HertzHandlerFunc 是 HertzHandler 的便捷写法,接 http.HandlerFunc 而不是 http.Handler。
func NativeStaticFSHandler ¶ added in v0.6.0
func NativeStaticFSHandler(prefix string, fsys fs.FS, opts ...NativeStaticOption) app.HandlerFunc
NativeStaticFSHandler 返回真正「零 adaptor 转换」的 Hertz 原生静态 handler。
与 StaticFSHandler 的区别:后者内部仍是 adaptor.HertzHandler(http.FileServer), 每次请求都要过 net/http Request⇄RequestContext 适配;本 handler 直接 fs.ReadFile + c.SetStatusCode/c.Write,热路径上无转换、分配更少。
语义对齐 net/http.FileServer 的常见子集:
- Content-Type 走 mime.TypeByExtension(与 net/http 同表)
- 支持 HEAD(只回头不回体)
- 文件不存在/路径非法 → 404 + X-Content-Type-Options: nosniff
- 路径穿越:拒绝含 ".." / 非法字符的路径(fs.ValidPath)
缓存策略**不写死**:默认不发 Cache-Control,由调用方用 WithNativeCacheControl 注入,或在 Handler 外自行加头。
示例:
//go:embed static/*
var assets embed.FS
sub, _ := fs.Sub(assets, "static")
h.GET("/static/*filepath", adaptor.NativeStaticFSHandler("/static", sub,
adaptor.WithNativeCacheControl("no-cache")))
prefix 与路由参数 filepath 拼接后在 fsys 内查找("/static" + "/css/a.css" → 查 "css/a.css")。若 fsys 根下仍带同名目录,可继续传带目录的 FS。
func PerformRequest ¶ added in v0.6.0
func PerformRequest(e *route.Engine, method, url string, body *ut.Body, headers ...ut.Header) (int, []byte)
PerformRequest 以 ut 风格跑一次请求,但会先挂上 MockConn,使 adaptor 的 4 个导出 handler(HertzHandler / HertzHandlerFunc / StaticFSHandler / StaticDirHandler)可单测。返回状态码与响应字节。
响应来源两条路径:
- adaptor/HijackHandler:字节写进 MockConn(见 Out)
- 原生 handler(NativeStaticFSHandler 等 c.Write):走 ctx.Response, 本函数把状态行/头/体拼成 HTTP 报文返回,便于统一断言
func StaticDirHandler ¶
func StaticDirHandler(prefix, dir string) app.HandlerFunc
StaticDirHandler 用本地目录提供静态资源服务。开发模式(dev)用, 生产推荐 StaticFSHandler(embed.FS 不依赖运行时目录)。
注意:dir 路径是相对 server 启动时的工作目录;Docker 镜像里需要 把目录 COPY 进容器。
func StaticFSHandler ¶
func StaticFSHandler(prefix string, efs embed.FS) app.HandlerFunc
StaticFSHandler 用 embed.FS 提供静态资源服务(prefix = URL 前缀, "/static/*filepath")。封装 net/http.FileServer(http.FS(efs)) + adaptor.HertzHandler + http.StripPrefix,业务 1 行挂载:
//go:embed static/*
var staticFS embed.FS
h.GET("/static/*filepath", hertzadaptor.StaticFSHandler("/static", staticFS))
前缀解析规则(2026-09-05 复审修复:原实现 fs.Sub(efs, "/static") 被 fs.ValidPath 拒绝前导斜杠 → 永远 404;且无 StripPrefix,子 FS 双重前缀):
- embed 根下存在同名目录(trim 斜杠后,如 "static"):以该目录为根;
- 否则以 embed 根为根(官方 http-adaptor 教程模式:FileServer 直接 解析完整路径,前缀目录在 embed 内部)。
两种情况都做 StripPrefix:FileServer 只看到前缀后的子路径。
官方依据:https://www.cloudwego.io/zh/docs/hertz/tutorials/basic-feature/http-adaptor/ 例子:
staticFS := adaptor.HertzHandler(http.FileServer(http.FS(staticFiles)))
h.GET("/static/*filepath", staticFS)
注意:内部仍是 adaptor.HertzHandler(http.FileServer),每次请求过 net/http ⇄ RequestContext 转换。静态资源热路径想要零转换请用 NativeStaticFSHandler。
Types ¶
type MockConn ¶ added in v0.6.0
type MockConn struct {
// contains filtered or unexported fields
}
MockConn 是给 adaptor handler 单测用的 network.Conn 实现。
背景(cloudwego/hertz#common/adaptor):adaptor 的 http.ResponseWriter 通过 rc.GetWriter() 写响应;ut.PerformRequest 从不 SetConn,GetWriter() 为 nil, WriteHeader 直接空指针。本类型补上 Writer/Reader 骨架,让 4 个导出 handler 可用 ut 风格单测。
注意:adaptor 路径的响应体写进 MockConn 的缓冲(见 Out()),**不会**出现在 ctx.Response.Body()——那是 HijackWriter 直写 conn 的结果,不是 mock 写错了。
func MustGetConn ¶ added in v0.6.0
func MustGetConn(ctx *app.RequestContext) (*MockConn, error)
MustGetConn 从 RequestContext 取出 PerformRequest 注入的 MockConn。 在自定义 handler 里断言写出内容时使用。
func (*MockConn) RemoteAddr ¶ added in v0.6.0
func (*MockConn) SetReadDeadline ¶ added in v0.6.0
func (*MockConn) SetReadTimeout ¶ added in v0.6.0
func (*MockConn) SetWriteDeadline ¶ added in v0.6.0
func (*MockConn) SetWriteTimeout ¶ added in v0.6.0
type NativeStaticOption ¶ added in v0.6.0
type NativeStaticOption func(*nativeStaticConfig)
NativeStaticOption 配置 NativeStaticFSHandler。
func WithNativeCacheControl ¶ added in v0.6.0
func WithNativeCacheControl(v string) NativeStaticOption
WithNativeCacheControl 设置 Cache-Control 响应头。默认不发送——缓存策略归调用方。
func WithNativeHeader ¶ added in v0.6.0
func WithNativeHeader(k, v string) NativeStaticOption
WithNativeHeader 追加自定义响应头(同名覆盖)。