Skip to main content

API Data Response

In modern web applications, especially those using frontend and backend separation, data is typically returned in JSON format. The WriteJson method mentioned earlier simply converts provided data to JSON format for response. In practical development, JSON data often follows a structured format like the one below (specific projects may vary but generally adhere to similar structures):

{
"code": 0, // Custom code to indicate success or failure of the request
"msg": "请求成功", // Message providing information; if there's an error, it contains error details
"data": {} // Data returned by the request; typically null if there's an error
}

GoFrame provides excellent support for API development in frontend-backend separation scenarios. Using the api module simplifies the creation of such response structures without needing custom definitions.

Here are the steps:

  • Define request and response data structures in the api module:
type ApiReq struct {
g.Meta `path:"/api" method:"all"`
}

type ApiRes struct {
UserName string `json:"name"`
UserAge int `json:"age"`
List g.Array `json:"list"`
}
  • Define corresponding methods in the controller:
func (c *Controller) Api(ctx context.Context, req *api.ApiReq) (res *api.ApiRes, err error) {
return
}

Instantiate response data and return:

res = &api.ApiRes{
UserName: "张三",
UserAge: 120,
List: g.Array{1, 2, 3, 4},
}
return

If there's an error, define the error message and return directly:

err = gerror.Newf("服务器开小差了")
return

Using the above method to return data automatically produces JSON data in the following format:

{
"code": 0,
"message": "",
"data": {
"name": "张三",
"age": 120,
"list": [1, 2, 3, 4]
}
}

The formatting of the data above is facilitated by the ghttp.MiddlewareHandlerResponse middleware. In actual applications, you can create custom middleware to define the desired data response format as needed.