The GoFrame framework has built-in powerful routing capabilities and offers superior routing features compared to similar frameworks. It supports popular named matching rules, fuzzy matching rules, and field matching rules, along with an excellent priority management mechanism.

An Example

Before diving into the core content of this chapter, let’s look at a simple example of using dynamic routing:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/net/ghttp"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/:name", func(r *ghttp.Request){
  9. r.Response.Writeln(r.Router.Uri)
  10. })
  11. s.BindHandler("/:name/update", func(r *ghttp.Request){
  12. r.Response.Writeln(r.Router.Uri)
  13. })
  14. s.BindHandler("/:name/:action", func(r *ghttp.Request){
  15. r.Response.Writeln(r.Router.Uri)
  16. })
  17. s.BindHandler("/:name/*any", func(r *ghttp.Request){
  18. r.Response.Writeln(r.Router.Uri)
  19. })
  20. s.BindHandler("/user/list/{field}.html", func(r *ghttp.Request){
  21. r.Response.Writeln(r.Router.Uri)
  22. })
  23. s.SetPort(8199)
  24. s.Run()
  25. }

The example above demonstrates the three types of fuzzy matching routing rules supported by the goframe framework: :name, *any, {field}, representing named matching rules, fuzzy matching rules, and field matching rules respectively. Different rules use the / symbol to separate levels, and the routing lookup uses a depth-first algorithm, where rules with deeper levels have higher priority. Let’s run the example and see the effect by accessing some URLs:

  1. URL Result
  2. http://127.0.0.1:8199/user/list/2.html /user/list/{field}.html
  3. http://127.0.0.1:8199/user/update /:name/update
  4. http://127.0.0.1:8199/user/info /:name/:action
  5. http://127.0.0.1:8199/user /:name/*any

In this example, we can also see that due to priority restrictions, the route rule /:name will be overridden by the /:name/*any rule, so it will not be matched. Therefore, when assigning route rules, unified planning and management are needed to avoid such situations.

Registration Rules

Route Registration Parameters

The most basic method for binding routes is the BindHandler method. Let’s take a look at the prototype of the BindHandler method we’ve been using:

  1. func (s *Server) BindHandler(pattern string, handler interface{})

pattern Parameter

The pattern is a route registration rule string, used in other route registration methods as well. The parameter format is as follows:

  1. [HTTPMethod:]RoutePattern[@Domain]

In which HTTPMethod (GET/PUT/POST/DELETE/PATCH/HEAD/CONNECT/OPTIONS/TRACE) and @Domain are optional parameters. In most scenarios, you can directly provide the route rule parameter, and BindHandler will automatically bind all request methods. If HTTPMethod is specified, the route rule will only be valid for that request method. By specifying @Domain, the rule will only be valid under that domain.

Router - Route Patterns - 图1tip

BindHandler is the most native method for registering routes. In most scenarios, we usually use group routing to manage reasons, which will be introduced in later chapters: Registration - Group Routing.

handler Parameter

The handler parameter is usually used to specify the route function. Our most basic examples use a function to register routes; a route function needs to meet the following definition, meaning it only needs to be able to receive the request object ghttp.Request:

  1. func(r *ghttp.Request) {
  2. // ...
  3. }

Let’s look at an example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/net/ghttp"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. func main() {
  7. s := g.Server()
  8. // This route rule will only be valid under GET requests
  9. s.BindHandler("GET:/{table}/list/{page}.html", func(r *ghttp.Request){
  10. r.Response.WriteJson(r.Router)
  11. })
  12. // This route rule will only be valid under GET requests and the localhost domain
  13. s.BindHandler("GET:/order/info/{order_id}@localhost", func(r *ghttp.Request){
  14. r.Response.WriteJson(r.Router)
  15. })
  16. // This route rule will only be valid under DELETE requests
  17. s.BindHandler("DELETE:/comment/{id}", func(r *ghttp.Request){
  18. r.Response.WriteJson(r.Router)
  19. })
  20. s.SetPort(8199)
  21. s.Run()
  22. }

The returned parameter r.Router provides information on the current matched route rule. When accessing this method, the server will output information on the current matched route rule. After execution, we can test using the curl command in the terminal:

  1. $ curl -XGET http://127.0.0.1:8199/order/list/1.html
  2. {"Domain":"default","Method":"GET","Priority":3,"Uri":"/{table}/list/{page}.html"}
  3. $ curl -XGET http://127.0.0.1:8199/order/info/1
  4. Not Found
  5. $ curl -XGET http://localhost:8199/order/info/1
  6. {"Domain":"localhost","Method":"GET","Priority":3,"Uri":"/order/info/{order_id}"}
  7. $ curl -XDELETE http://127.0.0.1:8199/comment/1000
  8. {"Domain":"default","Method":"DELETE","Priority":2,"Uri":"/comment/{id}"}
  9. $ curl -XGET http://127.0.0.1:8199/comment/1000
  10. Not Found

Exact Matching Rules

Exact matching rules are the rules without any dynamic rules, such as user, order, info, etc., which are rules with a determined name. In most scenarios, exact matching rules are used together with dynamic rules for route registration (e.g., /:name/list, where level 1 :name is a named matching rule, and level 2 list is an exact matching rule).

Dynamic Routing Rules

Dynamic routing rules are divided into three types: named matching rules, fuzzy matching rules, and field matching rules. The underlying data structure of dynamic routing is a routing tree constructed by hash tables by levels and double-linked lists. The hash tables assist in efficiently matching the levels of the URI, and the data linked list is used for priority control; rules of the same level are sorted by priority, with higher-priority rules placed at the head of the list. The underlying routing rule matching calculation with the request URI uses regular expressions and optimally utilizes caching mechanisms for highly efficient execution.

All matched parameters will be passed to the business layer as Router parameters, which can be retrieved using the following method of the ghttp.Request object:

  1. func (r *Request) GetRouter(key string, def ...interface{}) *gvar.Var

You can also use the ghttp.Request.Get method to retrieve matched routing parameters.

Named Matching Rules

Uses the :name method for matching (name is a custom match name) and performs a named match for parameters at a specified level of the URI (similar to regular ([^/]+), this URI level must have a value). The corresponding matched parameters will be parsed into Router parameters and passed to the registered service API for use.

Matching example 1:

  1. rule: /user/:user
  2. /user/john match
  3. /user/you match
  4. /user/john/profile no match
  5. /user/ no match

Matching example 2:

  1. rule: /:name/action
  2. /john/name no match
  3. /john/action match
  4. /smith/info no match
  5. /smith/info/age no match
  6. /smith/action match

Matching example 3:

  1. rule: /:name/:action
  2. /john/name match
  3. /john/info match
  4. /smith/info match
  5. /smith/info/age no match
  6. /smith/action/del no match

Fuzzy Matching Rules

Uses the *any method for matching (any is a custom match name) for fuzzy matching of parameters after the specified position of the URI (similar to regular (.*), this URI level can be empty), and parses matched parameters into Router parameters to be passed to the registered service API for use.

Matching example 1:

  1. rule: /src/*path
  2. /src/ match
  3. /src/somefile.go match
  4. /src/subdir/somefile.go match
  5. /user/ no match
  6. /user/john no match

Matching example 2:

  1. rule: /src/*path/:action
  2. /src/ no match
  3. /src/somefile.go match
  4. /src/somefile.go/del match
  5. /src/subdir/file.go/del match

Matching example 3:

  1. rule: /src/*path/show
  2. /src/ no match
  3. /src/somefile.go no match
  4. /src/somefile.go/del no match
  5. /src/somefile.go/show match
  6. /src/subdir/file.go/show match
  7. /src/show match

Field Matching Rules

Uses the {field} method for matching (field is a custom match name), which can perform segment matches of parameters at any position in the URI (similar to regular ([\w\.\-]+), this URI level must have a value and multiple field matches can occur at the same level), and parses matched parameters into Router parameters to be passed to the registered service API for use.

Matching example 1:

  1. rule: /order/list/{page}.php
  2. /order/list/1.php match
  3. /order/list/666.php match
  4. /order/list/2.php5 no match
  5. /order/list/1 no match
  6. /order/list no match

Matching example 2:

  1. rule: /db-{table}/{id}
  2. /db-user/1 match
  3. /db-user/2 match
  4. /db/user/1 no match
  5. /db-order/100 match
  6. /database-order/100 no match

Matching example 3:

  1. rule: /{obj}-{act}/*param
  2. /user-delete/10 match
  3. /order-update/20 match
  4. /log-list match
  5. /log/list/1 no match
  6. /comment/delete/10 no match

Dynamic Route Example

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/net/ghttp"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. func main() {
  7. s := g.Server()
  8. // A simple paging route example
  9. s.BindHandler("/user/list/{page}.html", func(r *ghttp.Request){
  10. r.Response.Writeln(r.Get("page"))
  11. })
  12. // Mixing {xxx} rule with :xxx rule
  13. s.BindHandler("/{object}/:attr/{act}.php", func(r *ghttp.Request){
  14. r.Response.Writeln(r.Get("object"))
  15. r.Response.Writeln(r.Get("attr"))
  16. r.Response.Writeln(r.Get("act"))
  17. })
  18. // Mixing multiple fuzzy matching rules
  19. s.BindHandler("/{class}-{course}/:name/*act", func(r *ghttp.Request){
  20. r.Response.Writeln(r.Get("class"))
  21. r.Response.Writeln(r.Get("course"))
  22. r.Response.Writeln(r.Get("name"))
  23. r.Response.Writeln(r.Get("act"))
  24. })
  25. s.SetPort(8199)
  26. s.Run()
  27. }

After execution, we can test it using the curl command or a browser access method. Below are the test results:

  1. $ curl -XGET http://127.0.0.1:8199/user/list/1.html
  2. 1
  3. $ curl -XGET http://127.0.0.1:8199/user/info/save.php
  4. user
  5. info
  6. save
  7. $ curl -XGET http://127.0.0.1:8199/class3-math/john/score
  8. class3
  9. math
  10. john
  11. score

Priority Control

Priority control follows a depth-first strategy. Here’s a brief strategy calculation:

  1. Rules with deeper levels have higher priority;
  2. At the same level, exact matching has higher priority than fuzzy matching;
  3. Within the same level, fuzzy matching priority is: field matching > named matching > fuzzy matching;

Let’s see examples (the rule on the left has a higher priority than the one on the right):

  1. /:name > /*any
  2. /user/name > /user/:action
  3. /:name/info > /:name/:action
  4. /:name/:action > /:name/*action
  5. /:name/{action} > /:name/:action
  6. /src/path/del > /src/path
  7. /src/path/del > /src/path/:action
  8. /src/path/*any > /src/path