Route Prefix

Overview

In go-zero, we declared HTTP service via api language, and then generated HTTP service code via goctl, after our systematic introduction to API norm.

Routing prefix demand is very common in HTTP service development, for example, we differentiate versions by routing, or different services by routing, which are very common.

Route Prefix

Assuming that we have a user service, we need to route out different versions, we can use api language to state the route prefix:

  1. https://example.com/v1/users
  2. https://example.com/v2/users

In the above routes, we have distinguished the route by v1 and v2 by distinguishing between /users through api languages we can state the route prefix:

  1. syntax = "v1"
  2. type UserV1 {
  3. Name string `json:"name"`
  4. }
  5. type UserV2 {
  6. Name string `json:"name"`
  7. }
  8. @server (
  9. prefix: /v1
  10. )
  11. service user-api {
  12. @handler usersv1
  13. get /users returns ([]UserV1)
  14. }
  15. @server (
  16. prefix: /v2
  17. )
  18. service user-api {
  19. @handler usersv2
  20. get /users returns ([]UserV2)
  21. }

In the above, we have stated the routing processing function by server via prefix keywords and then by @handler so that we can distinguish different versions by routing prefix.

Below look briefly at the generated routing code:

  1. func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
  2. server.AddRoutes(
  3. []rest.Route{
  4. {
  5. Method: http.MethodGet,
  6. Path: "/users",
  7. Handler: usersv1Handler(serverCtx),
  8. },
  9. },
  10. rest.WithPrefix("/v1"),
  11. )
  12. server.AddRoutes(
  13. []rest.Route{
  14. {
  15. Method: http.MethodGet,
  16. Path: "/users",
  17. Handler: usersv2Handler(serverCtx),
  18. },
  19. },
  20. rest.WithPrefix("/v2"),
  21. )
  22. }

In the above, we can see that the prefix that we have declared is actually generating the code by rest.WithPrefix to declare the route prefix so that we can distinguish different versions by routing prefix.