Routing

Routing #

The gFly router only accept a URI and a implementation of IHandler interface

// IHandler Interface a handler request.
type IHandler interface {
    Validate(c *Ctx) error
    Handle(c *Ctx) error
}

You must register the corresponding handlers in the Web or API router in the following two files:

Web Router

app/http/routes/web_routes.go

API Router

app/http/routes/api_routes.go

Available Router Methods #

f.GET("/users", page.NewGetUserAPI())
f.POST("/user", page.NewAddUserAPI())
f.PUT("/user", page.NewUpdateUserAPI())
f.DELETE("/users", page.NewDeleteUserAPI())
f.PATCH("/users", page.NewUpdatePartUserAPI())

Dependency Injection #

An instance of the IHandler interface always receives c *gfly.Ctx as the primary context during the course of a Request lifecycle.

Group and Middleware in Router #

You can use router.Group() to create hierarchies for navigating and managing Routers. Or you can use router.Use() to use Middleware to increase efficiency in data filtering and delegate processing.

router.Group(prefixAPI, func(apiRouter *gfly.Group) {
    apiRouter.GET("/json", api.NewDefaultApi())
	
    // Group user routers
    apiRouter.Group("/users", func(groupUsers *gfly.Group) {
        // Use Middleware
        groupUsers.Use(middleware.RuleMiddlewareFunc, middleware.AuthMiddlewareFunc)

        groupUsers.GET("", users.NewGetUsersApi())
        groupUsers.POST("", users.NewCreateUserApi())
    })
})

Route Parameters #

Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user’s ID from the URL. You may do so by defining route parameters

router.GET("/user/{id}", page.NewGetUserAPI());

Get path parameter in controller

userIdStr := c.PathVal("id")

Pattern with suffix: /user/{user}_admin #

/user/gordon_admin               match
/user/you_admin                  match
/user/you                        no match

Optional parameters #

If you need define an optional parameters, add ? at the end of param name. {name?}

Regex validation #

If you need define a validation, you could use a custom regex for the paramater value, add : after the name. For example: {name:[a-zA-Z]{5}}.

Optional parameters and regex validation are compatibles, only add ? between the name and the regex. For example: {name?:[a-zA-Z]{5}}.

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:*}

/src/                     match
/src/somefile.go          match
/src/subdir/somefile.go   match