-
Notifications
You must be signed in to change notification settings - Fork 1
Routing
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)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 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 can be served using two different approaches:
- The
AddStaticorAddStaticWithPrefixfunctions on theRouter - A catch-all route and serving the file manually
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:
- Normal
Routes (including catch-alls) will be matched first; but - If a non-catch-all is found, then we will use that; otherwise
- 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: