Object Registering uses an instantiated object to execute route registration, with every request handled by this object (same object), which remains in memory without being released.

Related Methods:

  1. func (s *Server) BindObject(pattern string, object interface{}, methods ...string) error
  2. func (s *Server) BindObjectMethod(pattern string, object interface{}, method string) error
  3. func (s *Server) BindObjectRest(pattern string, object interface{}) error

Preliminary Convention: The methods that need to be registered for routes must be public methods and the method definition must be:

  1. func(r *ghttp.Request)

Otherwise, registration cannot be completed, and there will be an error prompt during route registration, such as:

  1. panic: API conversion: interface {} is xxx, not func(*ghttp.Request)

Object Registering - BindObject

We can complete object registration using the BindObject method.

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type Controller struct{}
  7. func (c *Controller) Index(r *ghttp.Request) {
  8. r.Response.Write("index")
  9. }
  10. func (c *Controller) Show(r *ghttp.Request) {
  11. r.Response.Write("show")
  12. }
  13. func main() {
  14. s := g.Server()
  15. c := new(Controller)
  16. s.BindObject("/object", c)
  17. s.SetPort(8199)
  18. s.Run()
  19. }

As shown, an object is generated during route registration (the object is generated when the Server is started), and no matter how many requests come in afterward, the Server will delegate the request to the corresponding method of the object for processing. After executing this example, the output route table in the terminal is as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|---------------|--------------------------|------------|
  3. default | default | :8199 | ALL | /object | main.(*Controller).Index |
  4. |---------|---------|---------|--------|---------------|--------------------------|------------|
  5. default | default | :8199 | ALL | /object/index | main.(*Controller).Index |
  6. |---------|---------|---------|--------|---------------|--------------------------|------------|
  7. default | default | :8199 | ALL | /object/show | main.(*Controller).Show |
  8. |---------|---------|---------|--------|---------------|--------------------------|------------|

You can then view the effect via http://127.0.0.1:8199/object/show.

Registration - Object - 图1tip

The Index method in the controller is a special method; for example, when the registered route rule is /user, an HTTP request to /user will automatically map to the controller’s Index method. That is, accessing /user and /user/index will have the same execution effect.

Built-In Route Variables

When using the BindObject method for object registration, two built-in variables can be used in the route rule: {.struct} and {.method}. The former represents the current object name, and the latter the current registered method name. Let’s take a look at an example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type Order struct{}
  7. func (o *Order) List(r *ghttp.Request) {
  8. r.Response.Write("list")
  9. }
  10. func main() {
  11. s := g.Server()
  12. o := new(Order)
  13. s.BindObject("/{.struct}-{.method}", o)
  14. s.SetPort(8199)
  15. s.Run()
  16. }

After execution, the terminal outputs the route table as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-------------|--------------------|------------|
  3. default | default | :8199 | ALL | /order-list | main.(*Order).List |
  4. |---------|---------|---------|--------|-------------|--------------------|------------|

We can try accessing http://127.0.0.1:8199/order-list, and the page will output list. If you don’t use built-in variables in the route rule, then by default, the method will be appended to the end of the specified route rule.

Naming Conventions

When registering routes through objects, route rules can be automatically generated according to the object and method names. The default route rule is that when a method name contains multiple words (words are distinguished by capitalized characters), the route controller automatically uses the hyphen - to connect them, so the method name needs to have a - when accessing.

For example, if the method name is UserName, the generated route will be user-name; if the method name is ShowListItems, the generated route will be show-list-items, and so on.

Additionally, we can use the .Server.SetNameToUriType method to set how route names are generated from object method names. Currently, there are 4 types supported, corresponding to 4 constant definitions:

  1. UriTypeDefault = 0 // (default) all lowercase, words connected by '-'
  2. UriTypeFullName = 1 // no processing, use the original name to build the URI
  3. UriTypeAllLower = 2 // lowercase only, no connecting symbols between words
  4. UriTypeCamel = 3 // camel case naming

Note: Set this parameter before registering routes through the object, as it will not be effective after the registration. The default rule will be used.

Let’s look at an example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type User struct{}
  7. func (u *User) ShowList(r *ghttp.Request) {
  8. r.Response.Write("list")
  9. }
  10. func main() {
  11. u := new(User)
  12. s1 := g.Server("UriTypeDefault")
  13. s2 := g.Server("UriTypeFullName")
  14. s3 := g.Server("UriTypeAllLower")
  15. s4 := g.Server("UriTypeCamel")
  16. s1.SetNameToUriType(ghttp.UriTypeDefault)
  17. s2.SetNameToUriType(ghttp.UriTypeFullName)
  18. s3.SetNameToUriType(ghttp.UriTypeAllLower)
  19. s4.SetNameToUriType(ghttp.UriTypeCamel)
  20. s1.BindObject("/{.struct}/{.method}", u)
  21. s2.BindObject("/{.struct}/{.method}", u)
  22. s3.BindObject("/{.struct}/{.method}", u)
  23. s4.BindObject("/{.struct}/{.method}", u)
  24. s1.SetPort(8100)
  25. s2.SetPort(8200)
  26. s3.SetPort(8300)
  27. s4.SetPort(8400)
  28. s1.Start()
  29. s2.Start()
  30. s3.Start()
  31. s4.Start()
  32. g.Wait()
  33. }

To demonstrate the effect contrast, this example uses a multi-Server run method, configuring and running different name conversion methods with different Servers, allowing us to conveniently access different Servers (bound to different ports) in the same program to see different results.

After execution, the terminal outputs the route table as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. -----------------|---------|---------|--------|-----------------|-----------------------|-------------
  3. UriTypeDefault | default | :8100 | ALL | /user/show-list | main.(*User).ShowList |
  4. -----------------|---------|---------|--------|-----------------|-----------------------|-------------
  5. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  6. ------------------|---------|---------|--------|----------------|-----------------------|-------------
  7. UriTypeFullName | default | :8200 | ALL | /User/ShowList | main.(*User).ShowList |
  8. ------------------|---------|---------|--------|----------------|-----------------------|-------------
  9. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  10. ------------------|---------|---------|--------|----------------|-----------------------|-------------
  11. UriTypeAllLower | default | :8300 | ALL | /user/showlist | main.(*User).ShowList |
  12. ------------------|---------|---------|--------|----------------|-----------------------|-------------
  13. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  14. ---------------|---------|---------|--------|----------------|-----------------------|-------------
  15. UriTypeCamel | default | :8400 | ALL | /user/showList | main.(*User).ShowList |
  16. ---------------|---------|---------|--------|----------------|-----------------------|-------------

You can visit the following URLs to get the desired results:

  1. http://127.0.0.1:8100/user/show-list
  2. http://127.0.0.1:8200/User/ShowList
  3. http://127.0.0.1:8300/user/showlist
  4. http://127.0.0.1:8400/user/showList

Object Method Registration

If there are several public methods in the controller, but you only want to register a few of them and not make others public, what should you do? We can replace the implementation by passing the third optional parameter to BindObject, which supports passing multiple method names separated by a comma , ( method names are case-sensitive).

Example usage:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type Controller struct{}
  7. func (c *Controller) Index(r *ghttp.Request) {
  8. r.Response.Write("index")
  9. }
  10. func (c *Controller) Show(r *ghttp.Request) {
  11. r.Response.Write("show")
  12. }
  13. func main() {
  14. s := g.Server()
  15. c := new(Controller)
  16. s.BindObject("/object", c, "Show")
  17. s.SetPort(8199)
  18. s.Run()
  19. }

After execution, the terminal outputs the route table as:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|--------------|-------------------------|------------|
  3. default | default | :8199 | ALL | /object/show | main.(*Controller).Show |
  4. |---------|---------|---------|--------|--------------|-------------------------|------------|

Binding Route Methods - BindObjectMethod

We can bind specified routes to specific methods ( method names are case-sensitive ) using the BindObjectMethod.

Registration - Object - 图2tip

The difference between BindObjectMethod and BindObject is that BindObjectMethod binds a specific method of the object to the specified route rule, with the third method parameter able to specify only one method name. In contrast, when registering with BindObject, all routes are generated according to rules based on object method names, and the third methods parameter can specify multiple method names for registration.

Here’s an example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type Controller struct{}
  7. func (c *Controller) Index(r *ghttp.Request) {
  8. r.Response.Write("index")
  9. }
  10. func (c *Controller) Show(r *ghttp.Request) {
  11. r.Response.Write("show")
  12. }
  13. func main() {
  14. s := g.Server()
  15. c := new(Controller)
  16. s.BindObjectMethod("/show", c, "Show")
  17. s.SetPort(8199)
  18. s.Run()
  19. }

After execution, the terminal outputs the route table as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-------|-------------------------|------------|
  3. default | default | :8199 | ALL | /show | main.(*Controller).Show |
  4. |---------|---------|---------|--------|-------|-------------------------|------------|

RESTful Object Registering - BindObjectRest

Controllers designed with the RESTful approach are typically used for API services. In this mode, the HTTP Method maps to the corresponding method name in the controller, for instance, the POST method will map to the Post method in the controller (public method, starting with an uppercase letter), and the DELETE method will map to the Delete method in the controller, and so on. Other methods not named using HTTP Method conventions, even if defined as public methods, will not be automatically registered and will be invisible to the application. Of course, if the controller does not define a method corresponding to the HTTP Method, the request under that Method will return HTTP Status 404.

Registration - Object - 图3warning

GoFrame's RESTful object registration method is a strict REST route registration method. We can consider the controller’s object as the resource in REST, and the HTTP Method methods as the resource operation methods in the REST specification. If you are not very familiar with the REST specification or do not want a very strict RESTful routing design, please ignore this section.

We can complete the REST object registration using the BindObjectRest method, as shown in the example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type Controller struct{}
  7. // RESTFul - GET
  8. func (c *Controller) Get(r *ghttp.Request) {
  9. r.Response.Write("GET")
  10. }
  11. // RESTFul - POST
  12. func (c *Controller) Post(r *ghttp.Request) {
  13. r.Response.Write("POST")
  14. }
  15. // RESTFul - DELETE
  16. func (c *Controller) Delete(r *ghttp.Request) {
  17. r.Response.Write("DELETE")
  18. }
  19. // This method cannot be mapped and will not be accessible
  20. func (c *Controller) Hello(r *ghttp.Request) {
  21. r.Response.Write("Hello")
  22. }
  23. func main() {
  24. s := g.Server()
  25. c := new(Controller)
  26. s.BindObjectRest("/object", c)
  27. s.SetPort(8199)
  28. s.Run()
  29. }

Upon execution, the terminal outputs the route table as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|---------|---------------------------|------------|
  3. default | default | :8199 | DELETE | /object | main.(*Controller).Delete |
  4. |---------|---------|---------|--------|---------|---------------------------|------------|
  5. default | default | :8199 | GET | /object | main.(*Controller).Get |
  6. |---------|---------|---------|--------|---------|---------------------------|------------|
  7. default | default | :8199 | POST | /object | main.(*Controller).Post |
  8. |---------|---------|---------|--------|---------|---------------------------|------------|

Constructor Method Init and Destructor Method Shut

The Init and Shut methods in objects are special methods that are automatically invoked by the Server during the HTTP request process (similar to constructor and destructor functions).

  1. Init Callback Method

A method for initialization when the object receives a request, which is called back before the service API is invoked.

Method definition:

  1. // "Constructor" object method
  2. func (c *Controller) Init(r *ghttp.Request) {
  3. }
  1. Shut Callback Method

Automatically called by the Server when the request ends, which can be used for the object to perform some cleanup operations.

Method definition:

  1. // "Destructor" object method
  2. func (c *Controller) Shut(r *ghttp.Request) {
  3. }

Let’s look at an example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. type Controller struct{}
  7. func (c *Controller) Init(r *ghttp.Request) {
  8. r.Response.Writeln("Init")
  9. }
  10. func (c *Controller) Shut(r *ghttp.Request) {
  11. r.Response.Writeln("Shut")
  12. }
  13. func (c *Controller) Hello(r *ghttp.Request) {
  14. r.Response.Writeln("Hello")
  15. }
  16. func main() {
  17. s := g.Server()
  18. c := new(Controller)
  19. s.BindObject("/object", c)
  20. s.SetPort(8199)
  21. s.Run()
  22. }

After execution, the terminal route table output is as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|---------------|--------------------------|------------|
  3. default | default | :8199 | ALL | /object/hello | main.(*Controller).Hello |
  4. |---------|---------|---------|--------|---------------|--------------------------|------------|

As shown, Init and Shut are not automatically registered as route methods, and when accessing http://127.0.0.1:8199/object/hello, the output result will be:

  1. Hello
  2. Shut