Exit, ExitAll, and ExitHook

  1. Exit: Only exits the current executing logic method without exiting the subsequent request flow, can be used as a substitute for return.
  2. ExitAll: Forcibly interrupts the current execution flow, and neither the subsequent logic in the current executing method nor all subsequent logic methods will be executed, commonly used for permission control.
  3. ExitHook: When multiple HOOK methods are matched to a route, the HOOK methods are executed in the order of route matching priority by default. When calling the ExitHook method in a HOOK method, subsequent HOOK methods will not be executed, similar to HOOK method overriding.
  4. These three exit functions are only effective in service functions and HOOK event callback functions and cannot control the execution flow of middleware.

Since the ExitAll and ExitHook methods are rarely used at the application layer, only the use of the Exit method is introduced here.

Response - Exit - 图1tip

The Exit* flow exit features are implemented using the panic...recover... mechanism at the underlying level, with CPU execution costs of approximately tens of nanoseconds (ns), improving usability with minimal runtime overhead.

Exit Return Method

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request) {
  9. if r.Get("type").Int() == 1 {
  10. r.Response.Writeln("john")
  11. }
  12. r.Response.Writeln("smith")
  13. })
  14. s.SetPort(8199)
  15. s.Run()
  16. }

After execution, we visit http://127.0.0.1:8199/?type=1, and see the page output:

  1. smith

Let’s slightly adjust the above code:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request) {
  9. if r.Get("type").Int() == 1 {
  10. r.Response.Writeln("john")
  11. r.Exit()
  12. }
  13. r.Response.Writeln("smith")
  14. })
  15. s.SetPort(8199)
  16. s.Run()
  17. }

After execution, we visit http://127.0.0.1:8199/?type=1 again, and see the page output:

In addition, the Response object provides many Write*Exit methods, which indicate that the content is output and the Exit method is immediately called to exit the current service method.