This commit is contained in:
oneao committed 2025-08-13 17:30:57 +08:00
1 parent 7552670e4a
commit 01ea998605
13 files changed
+173 -45

No files matched your search

@@ -31,32 +31,42 @@ func (b *BodyCache) Load(r *http.Request) ([]byte, error) {
return
}
b.Data = buf.Bytes()
// 重新设置请求体方便后续读取
r.Body = io.NopCloser(bytes.NewReader(b.Data))
})
return b.Data, b.Err
}
// Context 自定义请求上下文,封装了请求信息、响应写入器、路由参数、中间件处理等功能
// Context 自定义请求上下文
type Context struct {
writer http.ResponseWriter // HTTP 响应写入器,用于构造响应数据
request *http.Request // HTTP 请求对象,包含请求相关信息
params map[string]string // 路由参数,如动态路径中的变量值
index int // 当前执行的中间件/处理函数索引,用于控制 Next 调用流程
handlers []HandlerFunc // 本次请求的中间件和最终处理函数链
writer http.ResponseWriter
request *http.Request
params map[string]string
index int
handlers []HandlerFunc
bodyCache BodyCache // 请求体缓存,确保请求体只读一次且可多次读取
keys map[string]interface{} // 用于存储请求生命周期内的自定义数据(如用户信息、orgId等)
bodyCache BodyCache
keys map[string]interface{}
aborted bool // 是否中止
}
// Next 执行下一个中间件或处理函数
func (c *Context) Next() {
c.index++
if c.index < len(c.handlers) {
for c.index < len(c.handlers) {
if c.aborted {
break
}
c.handlers[c.index](c)
c.index++
}
}
// Abort 中断后续中间件/处理函数
func (c *Context) Abort() {
c.aborted = true
}
// Param 获取路由参数
func (c *Context) Param(key string) string {
return c.params[key]
@@ -76,7 +86,7 @@ func (c *Context) JSON(statusCode int, data interface{}) {
}
}
// Body 方便读取请求体,实际调用 BodyCache 的 Load 方法
// Body 方便读取请求体
func (c *Context) Body() ([]byte, error) {
return c.bodyCache.Load(c.request)
}