go web開發之iris(三)路由

1.普通路由

package main

import "github.com/kataras/iris"

func main() {
   app := iris.New()
   //GET 方法
   app.Get("/", handler)
   // POST 方法
   app.Post("/", handler)
   // PUT 方法
   app.Put("/", handler)
   // DELETE 方法
   app.Delete("/", handler)
   //OPTIONS 方法
   app.Options("/", handler)
   //TRACE 方法
   app.Trace("/", handler)
   //CONNECT 方法
   app.Connect("/", handler)
   //HEAD 方法
   app.Head("/", handler)
   // PATCH 方法
   app.Patch("/", handler)
   //任意的http請求方法如option等
   app.Any("/", handler)

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

// 處理函數
func handler(ctx iris.Context) {
   ctx.Writef("methdo:%s path:%s",ctx.Method(),ctx.Path())
}

2.路由分組

package main

import "github.com/kataras/iris"

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

   // 分組
   userRouter := app.Party("/user")
   // route: /user/{name}/home  例如:/user/dollarKiller/home
   userRouter.Get("/{name:string}/home", func(ctx iris.Context) {
      name := ctx.Params().Get("name")
      ctx.Writef("you name: %s",name)
   })
   // route: /user/post
   userRouter.Post("/post", func(ctx iris.Context) {
      ctx.Writef("method:%s,path;%s",ctx.Method(),ctx.Path())
   })


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

3.動態路由

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

   // 路由傳參
   app.Get("/username/{name}", func(ctx iris.Context) {
      name := ctx.Params().Get("name")
      fmt.Println(name)
   })

   // 設置參數
   app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) {
      i, e := ctx.Params().GetInt("id")
      if e != nil {
         ctx.WriteString("error you input")
      }

      ctx.WriteString(strconv.Itoa(i))
   })

   // 設置錯誤碼
   app.Get("/profile/{id:int min(1)}/friends/{friendid:int max(8) else 504}", func(ctx iris.Context) {
      i, _ := ctx.Params().GetInt("id")
      getInt, _ := ctx.Params().GetInt("friendid")
      ctx.Writef("Hello id:%d looking for friend id: ",i,getInt)
   })// 如果沒有傳遞所有路由的macros,這將拋出504錯誤代碼而不是404.

   // 正則表達式
   app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx iris.Context) {
      ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
   })

   app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章