File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -100,6 +100,49 @@ fmt.Println(*example.Oed) //Prints: 64 (64, because the ptr addr is nil when Set
100
100
101
101
```
102
102
103
+ It's also a very useful feature for web application which default values are needed while binding request json.
104
+
105
+ For example:
106
+ ``` go
107
+ type ExamplePostBody struct {
108
+ Foo *bool ` json:"foo" default:"true"` // <-- StructTag with a default key
109
+ Bar *string ` json:"bar" default:"example"`
110
+ Qux *int ` json:"qux" default:"22"`
111
+ Oed *int64 ` json:"oed" default:"64"`
112
+ }
113
+ ```
114
+
115
+ HTTP request seems like this:
116
+ ``` bash
117
+ curl --location --request POST ... \
118
+ ... \
119
+ --header ' Content-Type: application/json' \
120
+ --data-raw ' {
121
+ "foo": false,
122
+ "bar": "",
123
+ "qux": 0
124
+ }'
125
+ ```
126
+
127
+ Request handler:
128
+ ``` go
129
+ func PostExampleHandler (c *gin .Context ) {
130
+ var reqBody ExamplePostBody
131
+ if err := c.ShouldBindJSON (&reqBody); err != nil {
132
+ c.JSON (http.StatusBadRequest , nil )
133
+ return
134
+ }
135
+ defaults.SetDefaults (&reqBody)
136
+
137
+ fmt.Println (*reqBody.Foo ) // Prints: false (zero value `false` for bool but not for bool ptr)
138
+ fmt.Println (*reqBody.Bar ) // Prints: "" (print "" which set in advance, not "example" for default)
139
+ fmt.Println (*reqBody.Qux ) // Prints: 0 (0 instead of 22, did not confused from whether zero value is in json or not)
140
+ fmt.Println (*reqBody.Oed ) // Prints: 64 (In this case "oed" is not in req json, so set default 64)
141
+
142
+ ...
143
+ }
144
+ ```
145
+
103
146
License
104
147
-------
105
148
You can’t perform that action at this time.
0 commit comments