Basic Routing

  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) // equals to 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...

Parameters

Named Parameters

As you can see, :name is a named parameter. The values are accessible via Context.Params.

Named parameters only match a single path segment:

Pattern: /hello/:name

  1. /hello/foo match
  2. /hello/bar match
  3. /hello/foo/bar no match

Catch-All Parameters

The second type are catch-all parameters and have the form *name. Like the name suggests, they match everything. Therefore they must always be at the end of the pattern:

Pattern: /src/*filepath

  1. /src/ match
  2. /src/somefile.go match
  3. /src/subdir/somefile.go match

Retrieve Parameters

  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 allows to match parameter that contains escaped slash %2f.

  1. router.UseRawPath = true

Options

Route Name

Named route is used to generate URLs, see URL Generation.

Route Middleware

RouteMiddleware is an option that allows to plug middleware into particular route.

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