Skip to content

Commit cfceb7f

Browse files
committed
update readme: add informations about the default tag option usage
1 parent eda9c33 commit cfceb7f

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

README.md

+26-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,32 @@ The supported field types in the struct are:
8787

8888
Unsupported types are simply ignored, however custom types can be registered to be converted.
8989

90-
More examples are available on the Gorilla website: https://www.gorillatoolkit.org/pkg/schema
90+
## Setting Defaults
91+
92+
It is possible to set default values when encoding/decoding by using the `default` tag option. The value of `default` is applied when a field has a zero value, a pointer has a nil value, or a slice is empty.
93+
94+
```go
95+
type Person struct {
96+
Phone string `schema:"phone,default:+123456"` // custom name
97+
Age int `schema:"age,default:21"`
98+
Admin bool `schema:"admin,default:false"`
99+
Balance float64 `schema:"balance,default:10.0"`
100+
Friends []string `schema:friends,default:john|bob`
101+
}
102+
```
103+
104+
The `default` tag option is supported for the following types:
105+
106+
* bool
107+
* float variants (float32, float64)
108+
* int variants (int, int8, int16, int32, int64)
109+
* uint variants (uint, uint8, uint16, uint32, uint64)
110+
* string
111+
* a slice of the above types. As shown in the example above, `|` should be used to separate between slice items.
112+
* a pointer to one of the above types (pointer to slice and slice of pointers are not supported).
113+
114+
> [!NOTE]
115+
> Because primitive types like int, float, bool, unint and their variants have their default (or zero) values set by Golang, it is not possible to distinguish them from a provided value when decoding/encoding form values. In this case, the value provided by the `default` option tag will be always applied. For example, let's assume that the value submitted in the form for `balance` is `0.0` then the default of `10.0` will be applied, even if `0.0` is part of the form data for the `balance` field. In such cases, it is highly recommended to use pointers to allow schema to distinguish between when a form field has no provided value and when a form has a value equal to the corresponding default set by Golang for a particular type. If the type of the `Balance` field above is changed to `*float64`, then the zero value would be `nil`. In this case, if the form data value for `balance` is `0.0`, then the default will not be applied.
91116
92117
## License
93118

0 commit comments

Comments
 (0)