IRIS 系列(三) 中间件

一般我选择一个web 框架时,会把是否支持中间件、中间件是否易用作为一个关键指标。

中间件用途

中间件可以作用于全局,可以用作用户认证,权限判断、跨域等多种功能。如权限判断就可以比进入主代码处理之前将没有权限的访问拒绝。中间件很酷的事情就是可以在不同的项目中重用。

IRIS 中间件

我们举一个简单的例子,这个例子实现每个路由主处理需要的时间,用于查看程序性能。

 package main
 ​
 import (
 "fmt"
 "strconv"
 "time"
 ​
 "github.com/kataras/iris/v12"
 )
 ​
 func main() {
 app := iris.New()
 app.Use(begin)
 app.Done(end)
 ​
 app.Get("/", Index)
 app.Get("/hello/{name}", Hello)
 app.Run(iris.Addr(":8080"))
 }
 ​
 func begin(ctx iris.Context) {
 t := time.Now().UnixNano()
 str := strconv.FormatInt(t, 10)
 ctx.Request().Header.Set("begin", str)
 ctx.Next()
 }
 ​
 func end(ctx iris.Context) {
 t := time.Now().UnixNano()
 str := ctx.GetHeader("begin")
 t1, _ := strconv.ParseInt(str, 10, 64)
 elapse := t - t1
 fmt.Printf("url:%s 耗时 %dns\n", ctx.Path(), elapse)
 ctx.Next()
 }
 ​
 func Index(ctx iris.Context) {
 ctx.HTML("<b>index</b>")
 ctx.Next()
 }
 ​
 func Hello(ctx iris.Context) {
 name := ctx.Params().Get("name")
 ctx.WriteString("hello " + name)
 ctx.Next()
 }

访问http://localhost:8080/hell/john

Now listening on: http://localhost:8080
Application started. Press CMD+C to shut down.
url:/hello/john 耗时 20000ns

通过上述输出,我们可以看到中间都被执行了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容