Routing

Echo’s router is based on radix tree, makingroute lookup really fast. It leverages sync poolto reuse memory and achieve zero dynamic memory allocation with no GC overhead.

Routes can be registered by specifying HTTP method, path and a matching handler.For example, code below registers a route for method GET, path /hello and ahandler which sends Hello, World! HTTP response.

  1. // Handler
  2. func hello(c echo.Context) error {
  3. return c.String(http.StatusOK, "Hello, World!")
  4. }
  5. // Route
  6. e.GET("/hello", hello)

You can use Echo.Any(path string, h Handler) to register a handler for all HTTP methods.If you want to register it for some methods use Echo.Match(methods []string, path string, h Handler).

Echo defines handler function as func(echo.Context) error where echo.Context primarilyholds HTTP request and response interfaces.

Match-any

Matches zero or more characters in the path. For example, pattern /users/* willmatch:

  • /users/
  • /users/1
  • /users/1/files/1
  • /users/anything…

Path Matching Order

  • Static
  • Param
  • Match any

Example

  1. e.GET("/users/:id", func(c echo.Context) error {
  2. return c.String(http.StatusOK, "/users/:id")
  3. })
  4. e.GET("/users/new", func(c echo.Context) error {
  5. return c.String(http.StatusOK, "/users/new")
  6. })
  7. e.GET("/users/1/files/*", func(c echo.Context) error {
  8. return c.String(http.StatusOK, "/users/1/files/*")
  9. })

Above routes would resolve in the following order:

  • /users/new
  • /users/:id
  • /users/1/files/*

Routes can be written in any order.

Group

Echo#Group(prefix string, m …Middleware) *Group

Routes with common prefix can be grouped to define a new sub-router with optionalmiddleware. In addition to specified middleware group also inherits parent middleware.To add middleware later in the group you can use Group.Use(m …Middleware).Groups can also be nested.

In the code below, we create an admin group which requires basic HTTP authenticationfor routes /admin/*.

  1. g := e.Group("/admin")
  2. g.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
  3. if username == "joe" && password == "secret" {
  4. return true, nil
  5. }
  6. return false, nil
  7. }))

Route Naming

Each of the registration methods returns a Route object, which can be used to name a route after the registration. For example:

  1. route := e.POST("/users", func(c echo.Context) error {
  2. })
  3. route.Name = "create-user"
  4. // or using the inline syntax
  5. e.GET("/users/:id", func(c echo.Context) error {
  6. }).Name = "get-user"

Route names can be very useful when generating URIs from the templates, where you can’t access the handler references or when you have multiple routes with the same handler.

URI Building

Echo#URI(handler HandlerFunc, params …interface{}) can be used to generate URI for any handler with specified path parameters. It’s helpful to centralize all yourURI patterns which ease in refactoring your application.

For example, e.URI(h, 1) will generate /users/1 for the route registered below:

  1. // Handler
  2. h := func(c echo.Context) error {
  3. return c.String(http.StatusOK, "OK")
  4. }
  5. // Route
  6. e.GET("/users/:id", h)

In addition to Echo#URI, there is also Echo#Reverse(name string, params …interface{}) which is used to generate URIs based on the route name. For example a call to Echo#Reverse("foobar", 1234) would generate the URI /users/1234 if the foobar route is registered like below:

  1. // Handler
  2. h := func(c echo.Context) error {
  3. return c.String(http.StatusOK, "OK")
  4. }
  5. // Route
  6. e.GET("/users/:id", h).Name = "foobar"

List Routes

Echo#Routes() []*Route can be used to list all registered routes in the orderthey are defined. Each route contains HTTP method, path and an associated handler.

Example

  1. // Handlers
  2. func createUser(c echo.Context) error {
  3. }
  4. func findUser(c echo.Context) error {
  5. }
  6. func updateUser(c echo.Context) error {
  7. }
  8. func deleteUser(c echo.Context) error {
  9. }
  10. // Routes
  11. e.POST("/users", createUser)
  12. e.GET("/users", findUser)
  13. e.PUT("/users", updateUser)
  14. e.DELETE("/users", deleteUser)

Using the following code you can output all the routes to a JSON file:

  1. data, err := json.MarshalIndent(e.Routes(), "", " ")
  2. if err != nil {
  3. return err
  4. }
  5. ioutil.WriteFile("routes.json", data, 0644)

routes.json

  1. [
  2. {
  3. "method": "POST",
  4. "path": "/users",
  5. "name": "main.createUser"
  6. },
  7. {
  8. "method": "GET",
  9. "path": "/users",
  10. "name": "main.findUser"
  11. },
  12. {
  13. "method": "PUT",
  14. "path": "/users",
  15. "name": "main.updateUser"
  16. },
  17. {
  18. "method": "DELETE",
  19. "path": "/users",
  20. "name": "main.deleteUser"
  21. }
  22. ]