echo.Context
的核心功能是封装 HTTP 请求的上下文,提供了操作请求、响应、参数绑定等多种便捷方法。- 它继承了原生
context.Context
的能力,可以处理超时、取消等生命周期管理。 - 方法的顺序通常是:接收请求 -> 处理请求 -> 生成响应。
模仿 echo
框架最简单地封装一个 HTTP 请求
1. 定义 HTTP 请求和响应的封装结构
首先,我们需要定义一些基础结构体来封装 HTTP 请求、响应和上下文。
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
// 请求上下文,用来封装请求和响应
type Context struct {
Request *http.Request
Response http.ResponseWriter
}
// 创建一个新的请求上下文
func NewContext(w http.ResponseWriter, r *http.Request) *Context {
return &Context{
Request: r,
Response: w,
}
}
// 简单的封装:模拟 Echo 中的 String 响应方法
func (c *Context) String(statusCode int, message string) error {
c.Response.WriteHeader(statusCode)
_, err := c.Response.Write([]byte(message))
return err
}
// 获取路径参数
func (c *Context) Param(key string) string {
return c.Request.URL.Query().Get(key)
}
// 获取查询参数
func (c *Context) QueryParam(key string) string {
return c.Request.URL.Query().Get(key)
}
2. 创建一个路由和处理器
我们创建一个简单的路由和请求处理函数来处理 HTTP 请求。
// 路由和处理器结构
type Router struct {
routes map[string]func(*Context)
}
// 创建一个新的路由器
func NewRouter() *Router {
return &Router{routes: make(map[string]func(*Context))}
}
// 注册路由和处理器
func (r *Router) AddRoute(path string, handler func(*Context)) {
r.routes[path] = handler
}
// 处理请求
func (r *Router) HandleRequest(w http.ResponseWriter, r *http.Request) {
ctx := NewContext(w, r)
handler, ok := r.routes[r.URL.Path]
if ok {
handler(ctx)
} else {
http.NotFound(w, r)
}
}
3. 编写主函数和服务器启动
现在,我们将路由和处理器组合起来,并启动一个 HTTP 服务器。
func main() {
// 创建一个路由器
router := NewRouter()
// 注册路由和处理器
router.AddRoute("/", func(c *Context) {
name := c.QueryParam("name") // 获取查询参数
if name == "" {
name = "Guest"
}
message := fmt.Sprintf("Hello, %s!", name)
c.String(http.StatusOK, message) // 返回字符串响应
})
// 启动服务器
http.HandleFunc("/", router.HandleRequest)
fmt.Println("Server is running on port 8080...")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Error starting server:", err)
}
}
4. 运行代码并测试
go run main.go
5. 测试
- 打开浏览器或使用
curl
测试:http://localhost:8080/?name=John
会返回:Hello, John!
http://localhost:8080/
会返回:Hello, Guest!
(因为没有提供name
参数)
6. 总结
这个简化版的框架模仿了 echo
的一些基本功能,包含了:
- 请求上下文:封装请求信息,提供获取查询参数、路径参数、以及响应的接口。
- 路由处理:简单的路由机制,用于根据请求路径选择对应的处理函数。
- 响应封装:通过
String()
方法返回响应,可以继续扩展其他响应格式,如 JSON、HTML 等。