Guides
Guides

Basic Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions linked in chains, which are executed when the route is matched.

Route definition takes the following structure:

App.Get("/", HomeHandler)
App.Get("/p/:page/?", PageHandler)
App.Post("/comment/:id/", CommentHandler)

In the above example, we added 3 routing rules. They are:

  • HTTP GET method on the path /
    If the application is hosted on http://example.com and the user visits the root URL http://example.com/, the request will be passed to HomeHandler.
  • HTTP GET method on the path /p/:page/?
    Every request with a path matching this routing rule, e.g. /p/1/, /p/101/ or /p/12345 will be passed to PageHandler, and what the user inputted in the page field will be stored in ctx.Params. Please notice that the last question mark ? in the routing rule means that the previous / is optional, and both /p/123/ and /p/123 can be matched.
  • HTTP POST method on the path /comment/:id/
    This is similar to the previous one. The only difference is that this one matches a POST method.

The parameters will be passed in ctx.Params, and can be get by this:

val := ctx.Params("page")

Other than GET and POST, you can use methods App.Put and App.Delete to handle PUT and DELETE requests.