Files
workspace/code/go-project/base-farmework/pkg/router/context.go
T
2025-08-11 21:32:08 +08:00

42 lines
893 B
Go

package router
import (
"encoding/json"
"net/http"
)
type Context struct {
Writer http.ResponseWriter
Request *http.Request
Params map[string]string
index int
handlers []HandlerFunc
}
// Next 执行下一个中间件或处理函数
func (c *Context) Next() {
c.index++
if c.index < len(c.handlers) {
c.handlers[c.index](c)
}
}
// Param 获取路由参数
func (c *Context) Param(key string) string {
return c.Params[key]
}
// Header 获取请求头
func (c *Context) Header(key string) string {
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)
}
}