Allowing Cross-Origin Requests

The first example is a common functional requirement.

We need to add a response Header to allow cross-origin requests before all API requests. This can be achieved through middleware:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func MiddlewareCORS(r *ghttp.Request) {
  7. r.Response.CORSDefault()
  8. r.Middleware.Next()
  9. }
  10. func main() {
  11. s := g.Server()
  12. s.Group("/api.v2", func(group *ghttp.RouterGroup) {
  13. group.Middleware(MiddlewareCORS)
  14. group.ALL("/user/list", func(r *ghttp.Request) {
  15. r.Response.Writeln("list")
  16. })
  17. })
  18. s.SetPort(8199)
  19. s.Run()
  20. }

After execution, the terminal prints the routing table information as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-------------------|-------------------|---------------------|
  3. default | default | :8199 | ALL | /api.v2/user/list | main.main.func1.1 | main.MiddlewareCORS
  4. |---------|---------|---------|--------|-------------------|-------------------|---------------------|

Here, we use group.Middleware(MiddlewareCORS) to register the cross-origin middleware to all service functions under the /api.v2 route in a grouped routing manner. We can then request http://127.0.0.1:8199/api.v2/user/list to see if the Header information allowing cross-origin requests is returned.

Middleware - Examples - 图1

Request Authentication Handling

We add an authentication middleware on top of the cross-origin middleware.

To simplify the example, in this demonstration, authentication is passed if the request contains a token parameter with the value 123456; otherwise, a 403 Forbidden status code is returned.

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. func MiddlewareAuth(r *ghttp.Request) {
  8. token := r.Get("token")
  9. if token.String() == "123456" {
  10. r.Response.Writeln("auth")
  11. r.Middleware.Next()
  12. } else {
  13. r.Response.WriteStatus(http.StatusForbidden)
  14. }
  15. }
  16. func MiddlewareCORS(r *ghttp.Request) {
  17. r.Response.Writeln("cors")
  18. r.Response.CORSDefault()
  19. r.Middleware.Next()
  20. }
  21. func main() {
  22. s := g.Server()
  23. s.Group("/api.v2", func(group *ghttp.RouterGroup) {
  24. group.Middleware(MiddlewareCORS, MiddlewareAuth)
  25. group.ALL("/user/list", func(r *ghttp.Request) {
  26. r.Response.Writeln("list")
  27. })
  28. })
  29. s.SetPort(8199)
  30. s.Run()
  31. }

After execution, the terminal prints the routing table information as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-------------------|-------------------|-----------------------------------------|
  3. default | default | :8199 | ALL | /api.v2/user/list | main.main.func1.1 | main.MiddlewareCORS,main.MiddlewareAuth
  4. |---------|---------|---------|--------|-------------------|-------------------|-----------------------------------------|

As you can see, our service method is bound with two middlewares, a cross-origin middleware and an authentication middleware. Requests will execute the MiddlewareCORS global middleware first, followed by the MiddlewareAuth group middleware, according to their registered order. We can then request http://127.0.0.1:8199/api.v2/user/list and http://127.0.0.1:8199/api.v2/user/list?token=123456 to compare the effects.

Middleware - Examples - 图2

Middleware - Examples - 图3

Handling Authentication Exceptions

Group routing middleware makes it convenient to add authentication exceptions, as only service methods registered under the current group route will bind and execute the authentication middleware; otherwise, the authentication middleware will not be executed.

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. func MiddlewareAuth(r *ghttp.Request) {
  8. token := r.Get("token")
  9. if token.String() == "123456" {
  10. r.Middleware.Next()
  11. } else {
  12. r.Response.WriteStatus(http.StatusForbidden)
  13. }
  14. }
  15. func main() {
  16. s := g.Server()
  17. s.Group("/admin", func(group *ghttp.RouterGroup) {
  18. group.ALL("/login", func(r *ghttp.Request) {
  19. r.Response.Writeln("login")
  20. })
  21. group.Group("/", func(group *ghttp.RouterGroup) {
  22. group.Middleware(MiddlewareAuth)
  23. group.ALL("/dashboard", func(r *ghttp.Request) {
  24. r.Response.Writeln("dashboard")
  25. })
  26. })
  27. })
  28. s.SetPort(8199)
  29. s.Run()
  30. }

After execution, the terminal prints the routing table information as follows:

  1. SERVER | ADDRESS | DOMAIN | METHOD | P | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|---|------------------|---------------------|---------------------|
  3. default | :8199 | default | ALL | 2 | /admin/dashboard | main.main.func1.2.1 | main.MiddlewareAuth
  4. |---------|---------|---------|--------|---|------------------|---------------------|---------------------|
  5. default | :8199 | default | ALL | 2 | /admin/login | main.main.func1.1 |
  6. |---------|---------|---------|--------|---|------------------|---------------------|---------------------|

We can see that only the service method of the /admin/dashboard route is bound with the authentication middleware main.MiddlewareAuth, whereas the service method of the /admin/login route does not have authentication processing added. We can then visit the following URLs to see the effect:

  1. http://127.0.0.1:8199/admin/login
  2. http://127.0.0.1:8199/admin/dashboard
  3. http://127.0.0.1:8199/admin/dashboard?token=123456

Middleware - Examples - 图4

Middleware - Examples - 图5

Middleware - Examples - 图6

Unified Error Handling

Based on middleware, we can perform some posterior judgments after the service function has been executed, especially for unified data format return, result processing, error judgment, etc. These requirements can be implemented using posterior middleware types. We use a simple example to demonstrate how to use middleware to do posterior judgment processing for all API requests, serving as an inspiration.

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. func MiddlewareAuth(r *ghttp.Request) {
  8. token := r.Get("token")
  9. if token.String() == "123456" {
  10. r.Middleware.Next()
  11. } else {
  12. r.Response.WriteStatus(http.StatusForbidden)
  13. }
  14. }
  15. func MiddlewareCORS(r *ghttp.Request) {
  16. r.Response.CORSDefault()
  17. r.Middleware.Next()
  18. }
  19. func MiddlewareErrorHandler(r *ghttp.Request) {
  20. r.Middleware.Next()
  21. if r.Response.Status >= http.StatusInternalServerError {
  22. r.Response.ClearBuffer()
  23. r.Response.Writeln("Oops, the server is taking a break, please try again later!")
  24. }
  25. }
  26. func main() {
  27. s := g.Server()
  28. s.Use(MiddlewareCORS)
  29. s.Group("/api.v2", func(group *ghttp.RouterGroup) {
  30. group.Middleware(MiddlewareAuth, MiddlewareErrorHandler)
  31. group.ALL("/user/list", func(r *ghttp.Request) {
  32. panic("db error: sql is xxxxxxx")
  33. })
  34. })
  35. s.SetPort(8199)
  36. s.Run()
  37. }

After execution, the terminal prints the routing table information as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-------------------|---------------------|-------------------------------------------------|
  3. default | default | :8199 | ALL | /* | main.MiddlewareCORS | GLOBAL MIDDLEWARE
  4. |---------|---------|---------|--------|-------------------|---------------------|-------------------------------------------------|
  5. default | default | :8199 | ALL | /api.v2/user/list | main.main.func1.1 | main.MiddlewareAuth,main.MiddlewareErrorHandler
  6. |---------|---------|---------|--------|-------------------|---------------------|-------------------------------------------------|

In this example, we determine whether there is a system error in the posterior middleware, and if there is, we return a fixed prompt message instead of displaying sensitive error messages to the user. Of course, in real project scenarios, it is often necessary to parse data in the return buffer, such as JSON data, and encapsulate it based on the current execution result to return a fixed data format, etc.

After executing this example, visit http://127.0.0.1:8199/api.v2/user/list?token=123456 to see the effect.

Middleware - Examples - 图7

Custom Log Handling

Let’s further refine the above example by outputting request logs, including status codes, to the terminal. Here we must use “global middleware” to intercept and handle all service requests, even 404 requests.

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. func MiddlewareAuth(r *ghttp.Request) {
  8. token := r.Get("token")
  9. if token.String() == "123456" {
  10. r.Middleware.Next()
  11. } else {
  12. r.Response.WriteStatus(http.StatusForbidden)
  13. }
  14. }
  15. func MiddlewareCORS(r *ghttp.Request) {
  16. r.Response.CORSDefault()
  17. r.Middleware.Next()
  18. }
  19. func MiddlewareLog(r *ghttp.Request) {
  20. r.Middleware.Next()
  21. errStr := ""
  22. if err := r.GetError(); err != nil {
  23. errStr = err.Error()
  24. }
  25. g.Log().Println(r.Response.Status, r.URL.Path, errStr)
  26. }
  27. func main() {
  28. s := g.Server()
  29. s.SetConfigWithMap(g.Map{
  30. "AccessLogEnabled": false,
  31. "ErrorLogEnabled": false,
  32. })
  33. s.Use(MiddlewareLog, MiddlewareCORS)
  34. s.Group("/api.v2", func(group *ghttp.RouterGroup) {
  35. group.Middleware(MiddlewareAuth)
  36. group.ALL("/user/list", func(r *ghttp.Request) {
  37. panic("Oops, I made a mistake!")
  38. })
  39. })
  40. s.SetPort(8199)
  41. s.Run()
  42. }

Middleware - Examples - 图8

Middleware - Examples - 图9

As you can see, we registered a global log handling middleware and cross-origin middleware, while the authentication middleware is registered under the /api.v2 route.

After execution, we can request http://127.0.0.1:8199/api.v2/user/list and http://127.0.0.1:8199/api.v2/user/list?token=123456 to compare the effects and check the log output in the terminal.