路由中间件
中间件
当我们在 iris 中讨论中间件的时候,我们就是在讨论运行一个 HTTP 请求处理器前后的代码。例如,日志中间件会把即将到来的请求明细写到日志中,然后在写响应日志详细之前,调用处理期代码。比较酷的是这些中间件是松耦合,而且可重用。
中间件仅仅是func(ctx iris.Context)
的处理器形式,中间件在前一个调用 ctx.Next()
时执行,这个可以用于去认证,例如,如果登录了,调用 ctx.Next()
否则将触发一个错误响应。
中间件开发
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
app.Get("/", before, mainHandler, after)
app.Run(iris.Addr(":8080"))
}
func before(ctx iris.Context) {
shareInformation := "this is a sharable information between handlers"
requestPath := ctx.Path()
println("Before the mainHandler: " + requestPath)
ctx.Values().Set("info", shareInformation)
ctx.Next() // 执行下一个处理器。
}
func after(ctx iris.Context) {
println("After the mainHandler")
}
func mainHandler(ctx iris.Context) {
println("Inside mainHandler")
// 获取 "before" 处理器中的设置的 "info" 值。
info := ctx.Values().GetString("info")
// 响应客户端
ctx.HTML("<h1>Response</h1>")
ctx.HTML("<br/> Info: " + info)
ctx.Next() // execute the "after".
}
$ go run main.go # and navigate to the http://localhost:8080
Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.
Before the mainHandler: /
Inside mainHandler
After the mainHandler
全局
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// 注册 "before" 处理器作为当前域名所有路由中第一个处理函数
// 或者使用 `UseGlobal` 去注册一个中间件,用于在所有子域名中使用
app.Use(before)
// 注册 "after" ,在所有路由的处理程序之后调用
app.Done(after)
// 注册路由
app.Get("/", indexHandler)
app.Get("/contact", contactHandler)
app.Run(iris.Addr(":8080"))
}
func before(ctx iris.Context) {
// [...]
}
func after(ctx iris.Context) {
// [...]
}
func indexHandler(ctx iris.Context) {
// 响应客户端
ctx.HTML("<h1>Index</h1>")
ctx.Next() // 执行通过 `Done` 注册的 "after" 处理器。
}
func contactHandler(ctx iris.Context) {
// 响应客户端
ctx.HTML("<h1>Contact</h1>")
ctx.Next() // 执行通过 `Done` 注册的 "after" 处理器。
}
探索
下面你将看到一些有用的处理程序的源代码:
一些确实能帮到你的中间件:
Middleware | Description | Example |
---|---|---|
jwt | 检查请求的 Authorization 头, 进行 JWT 检查和解析 |
iris-contrib/middleware/jwt/_example |
cors | HTTP跨域请求。 | iris-contrib/middleware/cors/_example |
secure | 一些快速安全实现的中间件。 | iris-contrib/middleware/secure/_example |
tollbooth | 用于验证HTTP请求速率的通用中间件 | iris-contrib/middleware/tollbooth/_example... |
cloudwatch | AWS cloudwatch 指标中间件。 | iris-contrib/middleware/cloudwatch/_exampl... |
new relic | 官方 New Relic Go Agent. | iris-contrib/middleware/newrelic/_example |
prometheus | 轻松为 prometheus 检测工具创建指标端点 | iris-contrib/middleware/prometheus/_exampl... |
casbin | 支持各种权限模型的授权库,例如 ACL, RBAC, ABAC | iris-contrib/middleware/casbin/_examples |
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。