Front-end and back-end interface interaction
We all know that the front-end usually obtains data through the interface provided by the background to complete the rendering of the front-end page. The front-end can be PC, M, applet, APP, etc.
I won't talk too much nonsense here, this is not the point.
Interface return value convention
return value specification
- Set the returned HTTP response status code;
- When an error occurs, it is necessary to set the error code and description information of the Response Body;
return correctly
The HTTP response status code is set to 200, and the Response Body structure is the returned data structure.
error return
HTTP response status code, do not set it to 200! RFC standards are required.
// Failure 错误时返回结构
type Failure struct {
Code int `json:"code"` // 业务码
Message string `json:"message"` // 描述信息
}
Unified definition of error codes
Error code specification
- Define error codes uniformly in one file;
- The length of the error code is 5 digits;
Bit 1 indicates what level the error is? For example: 1 is a system-level error, 2 is a business module error, and 9 error levels can be marked.
Bits 2 and 3 indicate which module is the error? For example: 01 is user module, 02 is order module, 99 modules can be marked.
The 4th and 5th digits indicate what is the specific error? For example: 01 means that the mobile phone number is invalid, 02 means that the input of the verification code is incorrect, and 99 errors can be marked.
How to use the Controller layer?
return correctly
res := new(createResponse)
res.Id = 1
ctx.Payload(res)
error return
c.AbortWithError(errno.NewError(
http.StatusBadRequest,
code.AdminCreateError,
code.Text(code.AdminCreateError)).WithErr(err),
)
return
Detailed code implementation
error code
- Error code encapsulation: github.com/xinliangnot…
- Define error codes: github.com/xinliangnot…
Controller
- github.com/xinliangnot…
Summarize
The above code is for your reference, and there is still room for optimization. You are welcome to use it and give your valuable opinions.