基本路由

  1. func index(ctx *clevergo.Context) error {
  2. return ctx.String(http.StatusOK, "hello world")
  3. }
  4. func hello(ctx *clevergo.Context) error {
  5. return ctx.String(http.StatusOK, fmt.Sprintf("hello %s", ctx.Params.String("name")))
  6. }
  7. router := clevergo.NewRouter()
  8. router.Get("/", index) // GET /
  9. // router.Handle(http.MethodGet, index) // 等同於 router.Get.
  10. router.Delete("/", index) // DELETE /
  11. router.Options("/", index) // OPTIONS /
  12. router.Patch("/", index) // PATCH /
  13. router.Post("/", index) // POST /
  14. router.Put("/", index) // PUT /
  15. router.Get("/hello/:name", hello) // GET /hello/foo, GET /hello/bar...

參數

命名參數

如你所看到的,:name 是一個命名參數,其值可以通過 Context.Params 獲得。 命名參數只匹配單個路徑段:

比如: /hello/:name

  1. /hello/foo 匹配
  2. /hello/bar 匹配
  3. /hello/foo/bar 不匹配

Catch-All 參數

第二種類型爲 catch-all 參數,形式爲 *name。如字面意思,它們匹配一切。因此它們必須位於 pattern 的末端。

比如: /src/*filepath

  1. /src/ 匹配
  2. /src/somefile.go 匹配
  3. /src/subdir/somefile.go 匹配

獲取參數

  1. func params(ctx *clevergo.Context) error {
  2. name := ctx.Params.String("name")
  3. page, err := ctx.Params.Int("page")
  4. num, err := ctx.Params.Int64("num")
  5. amount, err := ctx.Params.Uint64("amount")
  6. enable, err := ctx.Params.Bool("enable")
  7. price, err := ctx.Params.Float64("price")
  8. return err
  9. }

Raw Path

Router.UseRawPath 允許匹配帶有空格轉義符 %2f 的參數。

  1. router.UseRawPath = true

選項

命名路由

命名路由用於 URLs 生成,詳情參閱生成 URL

路由中間件

RouteMiddleware 選項允許爲特定的路由插入中間件。

  1. router.Post(
  2. "/posts",
  3. createPost,
  4. clevergo.RouteMiddleware(
  5. rateLimiter,
  6. bodyLimiter,
  7. // ...
  8. ),
  9. )