echo.Context(请求上下文)
- echo.Context 表示当前 HTTP 请求的上下文。通过路径、路径参数、数据、注册处理器和相关 API 进行请求的读取与响应的输出。由于 Context 是一个接口,也可以轻松地使用自定义 API 进行扩展。
HTTP:
- 包含Request和Response
- 简单来说,就是context封装了http请求和响应。
- 路径,路径参数,数据,注册处理器。属于我们这个请求的。
- API方法是属于context本身去处理请求和处理响应。
- Param(),QueryValue(),QueryParam()获取请求参数。
- JSON(),String(),HTML()处理响应。
扩展 Context
- 定义一个自定义 context
type CustomContext struct {
echo.Context
}
func (c *CustomContext) Foo() {
println("foo")
}
func (c *CustomContext) Bar() {
println("bar")
}
- 创建一个中间件来扩展默认的 context
e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := &CustomContext{c}
return h(cc)
}
})
此中间件应在任何其他中间件之前注册。
- 在处理器中使用
e.Get("/", func(c echo.Context) error {
cc := c.(*CustomContext)
cc.Foo()
cc.Bar()
return cc.String(200, "OK")
})
示例代码
package main
import (
"fmt"
"github.com/labstack/echo"
"net/http"
)
type MyContext struct {
echo.Context
}
func (c *MyContext) Foo(){
fmt.Print("Foo")
}
func main(){
e :=echo.New()
e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := &MyContext{c}
return h(cc)
}
})
e.GET("/",func (c echo.Context)error{
mc :=c.(*MyContext)
mc.Foo()
return mc.String(http.StatusOK,"context教程")
})
e.Logger.Fatal(e.Start(":1323"))
}