go web開發之iris(四)中間件Middleware

中間件主要用來處理頁面的登錄校驗、跨站請求僞造防禦、日誌記錄、session設置,權限管理等。
例如:可以對所有請求來之前做header中的頭部校驗
請求處理完成之後,調用ctx.Next()進行下一個階段的處理。

1.單個請求的中間件

func main() {
   app := iris.New()

   app.Get("/name/{name}",before,mainHandler,after)
   // before,mainHandler,after 感覺這個設計思路好像那個koa2
   // 前一個通過ctx.Next() 進入下一個方法

   app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
}

func before(ctx iris.Context)  {
   name := ctx.Params().Get("name")
   if strings.EqualFold(name,"dollarkiller") {
      fmt.Println("before...............")
      ctx.Next()
      return
   }
   ctx.WriteString("error none")
}

func after(ctx iris.Context) {
   fmt.Println("after.....................")
}

func mainHandler(ctx iris.Context) {
   fmt.Println("main.................")
   ctx.WriteString("ok........")
   ctx.Next()
}

2.全局中間件

func main() {
   app := iris.New()

   // 註冊前置全局中間件
   app.Use(before)
   // 主持後置
   app.Done(after)

   app.Get("/", func(ctx iris.Context) {
      ctx.HTML("<h1>Hello</h1>")
      ctx.Next()
   })

   app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
}

func before(ctx iris.Context)  {
   header := ctx.GetHeader("token")
   fmt.Println("全局前置..........",header)
   ctx.Next()
}

func after(ctx iris.Context)  {
   fmt.Println("後置............")
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章