Skip to content
This repository was archived by the owner on Jun 18, 2024. It is now read-only.

Routing

Luke edited this page Jul 16, 2016 · 10 revisions

Adding Routes

Goro uses a unified .Add function for all method types, as opposed to functions like .GET, .POST, etc to make it easy to move your code around. Also, Goro does not attach any Handler assignments to the route in the .Add function. This allows for flexible assignment of functionality to routes and allows you to split your code up however you want to.

To add a route using it's path format:

router.Add("GET", "/users/:id")

After that is done, you can attach your http.Handler or http.HandlerFunc. Goro uses plain old Go http handler types so it's safely interchangeable with plain old Go.

router.Add("GET", "/users/:id").HandleFunc(myHandlerFunc)

You can also create Route objects and assign them separately if you prefer to set up your workflow that way.

route := goro.NewRoute("GET", "/users/:id").HandleFunc(myHandlerFunc)
router.Use(route)

Format options

Goro routes accept 3 types of path segments:

  • Fixed values - These segments will be matched exactly. e.g.: /users.
  • Wildcard values / params - These segments will accept any value during matching and be saved so you can access them later. They always start with a colon (:). e.g.: /:id.
  • Variables - These segments will substitute a pre-defined variable value set by you using router.SetStringVariable(..). Variables always start with a dollar sign ($). e.g.: /$userIdPart.

Variables

Variables will be substituted exactly as they are defined so you can add multiple path segements into 1 variable if you like. They can also include wildcard segments. For example, if you define the following variable $userIdPart = /users/:id, then the definition /$userIdPart will result in a final path format value of /users/:id.

This in turn will be passed into the matcher and if wildcard values are found they will be assigned to params.

Static files

Static files can be served using two different approaches:

  1. The AddStatic or AddStaticWithPrefix functions on the Router
  2. A catch-all route and serving the file manually

AddStatic / AddStaticWithPrefix

How it plays nicely with other routes

The AddStatic and AddStaticWithPrefix functions operate as special routes within the Router. In order to allow for flexible static path matching whilst not interfering with the regular routing operations, there are a couple of "rules" (or hierarchies) to consider:

  1. Normal Routes (including catch-alls) will be matched first; but
  2. If a non-catch-all is found, then we will use that; otherwise
  3. If a catch-all is found, we will check first to see if there is a static match before executing the catch-all

Make sense?

If not, here is a longer example:

Catch-all static route