Mapping
The go-zero serialization and deserialization of text is used in three main places
- deserialization of http api request bodies
- Serialization of http api return body
- deserialization of configuration files
This article assumes that the reader has already defined the api file and modified the configuration file, if you are not familiar with it, you can refer to
#
1. deserialization of http api request bodyIn the deserialization process, go-zero implements its own deserialization mechanism for request data data format
and data validation
requirements
Data format
to order.api file as an example#
1.1 There are three types of tags for deserialization of http api request bodies.
path
: parameter deserialization in http url path/order/add/1234567
will resolve the token to 1234567
form
: http form form deserialization, you need to add Content-Type: multipart/form-data in the header/order/find/1234567?page=1&pageSize=20
will parse out the token as 1234567, page as 1 and pageSize as 20
json
: http request json body deserialization, need header header add Content-Type: application/json{"productId": "321", "num":1}
will parse out productId as 321 and num as 1
Data validation
using user.api file as an example#
1.2 There are many ways to validate data, including but not limited to.
age
: default is not entered as 20, enter then the range of values is (12:100], open and closed beforename
: required, cannot be emptyalias
: optional, can be emptysex
: required, the value ismale
orfemale
.avatar
: optional, default isdefault.png
See unmarshaler_test.go for more details
#
2. Serialization of http api return body- Use the official default
encoding/json
package for serialization, so I won't go over it here
#
3. deserialization of configuration filesConfiguration file deserialization
andhttp api request body deserialization
use the same set of parsing rules, seehttp api request body deserialization