在本部分中,你将学习如何覆盖现有的[Context](https://godoc.org/github.com/kataras/iris/context#Context) 的方法。
[Context](https://godoc.org/github.com/kataras/iris/context#Context) 是一个接口。但是正如你所知, 当用其他框架时,即使将其用作接口也没有重写功能。 使用 Iris 你可以使用 `app.ContextPool.Attach` 方法 ,将实现附加到Context池本身。
1. 让我们开始导入这里需要的 `"github.com/kataras/iris/v12/context"`
2. 其次,创建您自己的Context实现。
3. 添加 `Do` 和 `Next` 方法,它们仅调用 `context.Do` 和 `context.Next`包级函数。
4. 使用应用程序的 `ContextPool` 将其设置为应用于路由处理程序的 Context 实现。
示例代码:
请同时阅读注释。
```
package main
import (
"reflect"
"github.com/kataras/iris/v12"
// 1.
"github.com/kataras/iris/v12/context"
)
// 2.
// 创建你自己的自定义 Context,放入你需要的任何字段。
type MyContext struct {
// 嵌入 `iris.Context` -
// 这是完全可选的, 但如果你需要
// 不覆盖所有 Context 的方法!
iris.Context
}
// 可选: 验证 MyContext 实现 iris.Context 在编译的时候。
var _ iris.Context = &MyContext{}
// 3.
func (ctx *MyContext) Do(handlers context.Handlers) {
context.Do(ctx, handlers)
}
// 3.
func (ctx *MyContext) Next() {
context.Next(ctx)
}
// [在此处覆盖你想要的任何 Context 方法....]
// 像下面的HTML一样:
func (ctx *MyContext) HTML(format string, args ...interface{}) (int, error) {
ctx.Application().Logger().Infof("Executing .HTML function from MyContext")
ctx.ContentType("text/html")
return ctx.Writef(format, args...)
}
func main() {
app := iris.New()
// 4.
app.ContextPool.Attach(func() iris.Context {
return &MyContext{
// 如果你要使用嵌入式 Context,
// 调用 `context.NewContext` 创建一个:
Context: context.NewContext(app),
}
})
// 在 ./view/** 目录中的 .html 文件上注册视图引擎
app.RegisterView(iris.HTML("./view", ".html"))
// 照常注册路由
app.Handle("GET", "/", recordWhichContextForExample,
func(ctx iris.Context) {
// 使用 覆盖过的 Context 的 HTML 方法。
ctx.HTML("<h1> Hello from my custom context's HTML! </h1>")
})
// 当 MyContext 本身不直接定义 View 函数时,
// 这将由 MyContext.Context 嵌入默认 Context
app.Handle("GET", "/hi/{firstname:alphabetical}",recordWhichContextForExample,
func(ctx iris.Context) {
firstname := ctx.Values().GetString("firstname")
ctx.ViewData("firstname", firstname)
ctx.Gzip(true)
ctx.View("hi.html")
})
app.Run(iris.Addr(":8080"))
}
// 应该始终打印 "($PATH) Handler is executing from 'MyContext'"
func recordWhichContextForExample(ctx iris.Context) {
ctx.Application().Logger().Infof("(%s) Handler is executing from: '%s'",
ctx.Path(), reflect.TypeOf(ctx).Elem().Name())
ctx.Next()
}
```