API Import

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.

In HTTP service development, we all describe HTTP services through api description. As business volume increases, api files may grow larger, or we have some public structures. If we all write in the same api file, api files will become very large and not easy to read and maintain, we can use api import to solve these problems by introducing other api documents.

api files import

Assume that the response format of our HTTP service is uniform for the following json format:

  1. {
  2. "code": 0,
  3. "msg": "success",
  4. "data": {}
  5. }

As shown by the above mentioned json, we have code,msg,data fields in our response format, Medium code and msg are fixed, ata is variable, we can use 2 of these fields code,msg abstraction, defined as a public structure and then introduce this structure in other api files.

Example: Assuming that we have a user service to query user information and modify user information, we can reuse code and msg abstract in base.api, then reuse and define specific response structures in user.api.

  • base.api
  • user.api
  1. syntax = "v1"
  2. type Base {
  3. Code int `json:"code"`
  4. Msg string `json:"msg"`
  5. }
  1. syntax = "v1"
  2. // Import the base.api file
  3. import "base.api"
  4. type UserInfoReq {
  5. Id int64 `path:"id"`
  6. }
  7. type UserInfo {
  8. Id int64 `path:"id"`
  9. Name string `json:"name"`
  10. Age int `json:"age"`
  11. }
  12. type UserInfoResp {
  13. Base // Base is the public structure in base.api, in the API description language, there is no concept of package
  14. Data UserInfo `json:"data"`
  15. }
  16. type UserInfoUpdateReq {
  17. Id int64 `json:"id"`
  18. UserInfo
  19. }
  20. type UserInfoUpdateResp {
  21. Base
  22. }
  23. service user {
  24. @handler userInfo
  25. get /user/info/:id (UserInfoReq) returns (UserInfoResp)
  26. @handler userInfoUpdate
  27. post /user/info/update (UserInfoUpdateReq) returns (UserInfoUpdateResp)
  28. }
API Import - 图1tutorial

In api description, there is no package concept, so a relative path needs to be used when introducing other api files, such as import "base.api" in the example aboveand import "./base.api" can be used if it is in the same directory. Import supports relative and absolute paths.

In api description, we specify that all HTTP service statements are stored in main api, abstract structures are placed in other api files, and other api files are then introduced into main api files. This allows main api files to be simpler and easy to maintain, while service syntax blocks are not allowed in api files that will otherwise be misstated.

Warning:api import does not support circular import!!!