This commit is contained in:
oneao committed 2025-08-13 22:00:31 +08:00
1 parent 01ea998605
commit d1b1aafc57
9 files changed
+82 -35

No files matched your search

@@ -38,8 +38,8 @@ func (b *BodyCache) Load(r *http.Request) ([]byte, error) {
// Context 自定义请求上下文
type Context struct {
writer http.ResponseWriter
request *http.Request
Request *http.Request
Writer http.ResponseWriter
params map[string]string
index int
handlers []HandlerFunc
@@ -74,21 +74,21 @@ func (c *Context) Param(key string) string {
// Header 获取请求头
func (c *Context) Header(key string) string {
return c.request.Header.Get(key)
return c.Request.Header.Get(key)
}
// JSON 返回 JSON 格式响应
func (c *Context) JSON(statusCode int, data interface{}) {
c.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
c.writer.WriteHeader(statusCode)
if err := json.NewEncoder(c.writer).Encode(data); err != nil {
http.Error(c.writer, err.Error(), http.StatusInternalServerError)
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
c.Writer.WriteHeader(statusCode)
if err := json.NewEncoder(c.Writer).Encode(data); err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
}
}
// Body 方便读取请求体
func (c *Context) Body() ([]byte, error) {
return c.bodyCache.Load(c.request)
return c.bodyCache.Load(c.Request)
}
// BindJSON 反序列化 JSON 请求体到 obj
@@ -102,10 +102,10 @@ func (c *Context) BindJSON(obj interface{}) error {
// PostForm 获取表单参数
func (c *Context) PostForm(key string) string {
if err := c.request.ParseForm(); err != nil {
if err := c.Request.ParseForm(); err != nil {
return ""
}
return c.request.FormValue(key)
return c.Request.FormValue(key)
}
// Set 存储键值对
@@ -124,3 +124,29 @@ func (c *Context) Get(key string) (interface{}, bool) {
val, ok := c.keys[key]
return val, ok
}
// AddError 只记录错误对象
func (c *Context) AddError(err error) {
if err == nil {
return
}
if c.keys == nil {
c.keys = make(map[string]interface{})
}
if _, exists := c.keys["errors"]; !exists {
c.keys["errors"] = []error{}
}
c.keys["errors"] = append(c.keys["errors"].([]error), err)
}
// Errors 获取所有错误
func (c *Context) Errors() []error {
if c.keys == nil {
return nil
}
if errs, exists := c.keys["errors"]; exists {
return errs.([]error)
}
return nil
}