j
jaryue
V1
2023/03/29阅读:13主题:默认主题
gowebday5
package context5
import (
"encoding/json"
"fmt"
"net/http"
)
type H map[string]interface{}
type Context struct {
// origin objects
Writer http.ResponseWriter //Writer: 一个 http.ResponseWriter 类型的对象,用于将响应内容写入 HTTP 响应体。
Req *http.Request //Req: 一个 *http.Request 类型的指针,表示客户端发起的 HTTP 请求。
// request info
Path string //一个字符串,表示请求的 URL 路径。
Method string //一个字符串,表示请求的 HTTP 方法。get/post...
Params map[string]string //一个字符串到字符串的映射,表示 URL 查询参数或表单数据。
// response info
StatusCode int //一个整数,表示 HTTP 响应状态码。
// middleware
Handlers []HandlerFunc //handlers: 一个 HandlerFunc 类型的切片,表示当前请求需要经过的中间件函数列表。
Index int //index: 一个整数,表示当前执行到的中间件函数在 handlers 中的下标。可以理解为handers的下标
}
// HandlerFunc 是一个函数类型,它接受一个 *Context 类型的参数,表示当前请求的上下文信息。
type HandlerFunc func(*Context)
// NewContext: 一个工厂函数,用于创建一个 Context 类型的对象,并将其初始化为一个请求的上下文信息。
func NewContext(w http.ResponseWriter, req *http.Request) *Context {
return &Context{
Path: req.URL.Path,
Method: req.Method,
Req: req,
Writer: w,
Index: -1,
}
}
//添加核心:
//Next: 用于将请求传递给下一个中间件函数。
//类似于洋葱模型的处理方式,每一层中间件函数处理完后,需要将请求传递给下一层中间件函数,直到最后一个中间件函数处理完请求并返回响应。
// Next() 函数的作用就是将请求传递给下一个中间件函数。它的实现比较简单,主要分为以下两步:
// 将 index 的值加一,表示将要执行下一个中间件函数。
// 循环执行中间件函数列表中从 index 开始的函数,直到执行到最后一个中间件函数或者其中一个函数调用了 c.Next() 方法,停止循环并返回
func (c *Context) Next() {
c.Index++
s := len(c.Handlers)
for ; c.Index < s; c.Index++ {
c.Handlers[c.Index](c)
}
}
func (c *Context) Param(key string) string {
value, _ := c.Params[key]
return value
}
func (c *Context) PostForm(key string) string {
return c.Req.FormValue(key)
}
func (c *Context) Query(key string) string {
return c.Req.URL.Query().Get(key)
}
func (c *Context) Status(code int) {
c.StatusCode = code
c.Writer.WriteHeader(code)
}
func (c *Context) SetHeader(key string, value string) {
c.Writer.Header().Set(key, value)
}
func (c *Context) String(code int, format string, values ...interface{}) {
c.SetHeader("Content-Type", "text/plain")
c.Status(code)
c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}
func (c *Context) JSON(code int, obj interface{}) {
c.SetHeader("Content-Type", "application/json")
c.Status(code)
encoder := json.NewEncoder(c.Writer)
if err := encoder.Encode(obj); err != nil {
http.Error(c.Writer, err.Error(), 500)
}
}
func (c *Context) Data(code int, data []byte) {
c.Status(code)
c.Writer.Write(data)
}
func (c *Context) HTML(code int, html string) {
c.SetHeader("Content-Type", "text/html")
c.Status(code)
c.Writer.Write([]byte(html))
}
作者介绍
j
jaryue
V1