Debian Codegraph @

README.md

raw
1 # gofiber/schema
2
3 Package gofiber/schema converts structs to and from form values.
4
5 Per-commit benchmark charts: <https://gofiber.github.io/schema/benchmarks/>
6
7 ## Example
8
9 Here's a quick example: we parse POST form values and then decode them into a struct:
10
11 ```go
12 // Set a Decoder instance as a package global, because it caches
13 // meta-data about structs, and an instance can be shared safely.
14 var decoder = schema.NewDecoder()
15
16 type Person struct {
17 Name string
18 Phone string
19 }
20
21 func MyHandler(w http.ResponseWriter, r *http.Request) {
22 err := r.ParseForm()
23 if err != nil {
24 // Handle error
25 }
26
27 var person Person
28
29 // r.PostForm is a map of our POST form values
30 err = decoder.Decode(&person, r.PostForm)
31 if err != nil {
32 // Handle error
33 }
34
35 // Do something with person.Name or person.Phone
36 }
37 ```
38
39 Conversely, contents of a struct can be encoded into form values. Here's a variant of the previous example using the Encoder:
40
41 ```go
42 var encoder = schema.NewEncoder()
43
44 func MyHttpRequest() {
45 person := Person{"Jane Doe", "555-5555"}
46 form := url.Values{}
47
48 err := encoder.Encode(person, form)
49
50 if err != nil {
51 // Handle error
52 }
53
54 // Use form values, for example, with an http client
55 client := new(http.Client)
56 res, err := client.PostForm("http://my-api.test", form)
57 }
58
59 ```
60
61 To define custom names for fields, use a struct tag "schema". To not populate certain fields, use a dash for the name and it will be ignored:
62
63 ```go
64 type Person struct {
65 Name string `schema:"name,required"` // custom name, must be supplied
66 Phone string `schema:"phone"` // custom name
67 Admin bool `schema:"-"` // this field is never set
68 }
69 ```
70
71 The supported field types in the struct are:
72
73 * bool
74 * float variants (float32, float64)
75 * int variants (int, int8, int16, int32, int64)
76 * string
77 * uint variants (uint, uint8, uint16, uint32, uint64)
78 * struct
79 * a pointer to one of the above types
80 * a slice or a pointer to a slice of one of the above types
81
82 Unsupported types are simply ignored, however custom types can be registered to be converted.
83
84 ## Decoding Key/Value Pairs
85
86 When values arrive one key/value pair at a time, as a parsed query string's do, `DecodeValues` decodes the pairs without first building the map `Decode` takes:
87
88 ```go
89 keys := []string{"name", "phone", "phone"}
90 values := []string{"Jane Doe", "555-5555", "555-0100"}
91
92 err := decoder.DecodeValues(&person, keys, values)
93 ```
94
95 `values[i]` is a value of the key `keys[i]`, and a key given more than once has all of its values in the order given, as it would in the map. The two slices must be the same length.
96
97 ## Setting Defaults
98
99 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.
100
101 ```go
102 type Person struct {
103 Phone string `schema:"phone,default:+123456"` // custom name
104 Age int `schema:"age,default:21"`
105 Admin bool `schema:"admin,default:false"`
106 Balance float64 `schema:"balance,default:10.0"`
107 Friends []string `schema:friends,default:john|bob`
108 }
109 ```
110
111 The `default` tag option is supported for the following types:
112
113 * bool
114 * float variants (float32, float64)
115 * int variants (int, int8, int16, int32, int64)
116 * uint variants (uint, uint8, uint16, uint32, uint64)
117 * string
118 * a slice of the above types. As shown in the example above, `|` should be used to separate between slice items.
119 * a pointer to one of the above types (pointer to slice and slice of pointers are not supported).
120
121 > [!NOTE]
122 > 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.
123
124 <!-- skip-docs -->
125 ## ☕ Supporters
126
127 Fiber is an open-source project that runs on donations to pay the bills, e.g., our domain name, hosting, and serverless infrastructure. If you want to support Fiber, please become a [GitHub Sponsor](https://github.com/sponsors/gofiber).
128
129 <p align="center">
130 <a href="https://www.coderabbit.ai/?utm_source=gofiber&utm_medium=sponsor&utm_content=readme">
131 <picture>
132 <source media="(prefers-color-scheme: dark)" srcset="https://www.coderabbit.ai/images/logo-dark.svg">
133 <img width="280" height="52" alt="CodeRabbit" src="https://www.coderabbit.ai/images/logo-orange.svg">
134 </picture>
135 </a>
136 </p>
137 <p align="center">
138 <a href="https://blacksmith.sh/?utm_source=gofiber&utm_medium=sponsor&utm_content=readme">
139 <img width="280" height="96" alt="Blacksmith" src="https://raw.githubusercontent.com/gofiber/.github/main/assets/sponsors/blacksmith.png">
140 </a>
141 </p>
142 <p align="center">
143 <sub><b>Tool Sponsors</b> - supporting Fiber with free IDE licenses and AI credits</sub>
144 </p>
145 <p align="center">
146 <a href="https://www.jetbrains.com/?from=gofiber" title="JetBrains - IDE licenses"><img width="36" height="36" alt="JetBrains" src="https://github.com/JetBrains.png?size=72"></a>
147 &nbsp;
148 <a href="https://openai.com/?utm_source=gofiber&utm_medium=sponsor&utm_content=readme" title="OpenAI - AI credits"><img width="36" height="36" alt="OpenAI" src="https://github.com/openai.png?size=72"></a>
149 &nbsp;
150 <a href="https://www.anthropic.com/?utm_source=gofiber&utm_medium=sponsor&utm_content=readme" title="Anthropic - AI credits"><img width="36" height="36" alt="Anthropic" src="https://github.com/anthropics.png?size=72"></a>
151 </p>
152
153 <!-- sponsors -->
154
155 ### 📅 Monthly Sponsors
156
157 <table>
158 <tr><td valign="top"><strong>ðŸ”Ĩ Fiber Guardian</strong></td><td><a href="https://www.coderabbit.ai/?utm_source=cr_org&amp;utm_medium=github" title="@coderabbitai"><img src="https://github.com/coderabbitai.png" width="50" alt="@coderabbitai" /></a></td></tr>
159 <tr><td valign="top"><strong>☕ Fiber Supporter</strong></td><td><a href="https://ndole.studio" title="@NdoleStudio"><img src="https://github.com/NdoleStudio.png" width="34" alt="@NdoleStudio" /></a></td></tr>
160 <tr><td valign="top"><strong>ðŸŠī Fiber Friend</strong></td><td><a href="https://github.com/simonheisstpeter" title="@simonheisstpeter"><img src="https://github.com/simonheisstpeter.png" width="32" alt="@simonheisstpeter" /></a></td></tr>
161 </table>
162
163 ### 🎁 One-time Sponsors
164
165 <table>
166 <tr><td valign="top"><strong>🚀 Fiber Hero</strong></td><td><a href="https://www.thanks.dev" title="@thnxdev"><img src="https://github.com/thnxdev.png" width="40" alt="@thnxdev" /></a></td></tr>
167 <tr><td valign="top"><strong>ðŸŠī Fiber Friend</strong></td><td><a href="https://github.com/Gl1tchedPixzl" title="@Gl1tchedPixzl"><img src="https://github.com/Gl1tchedPixzl.png" width="26" alt="@Gl1tchedPixzl" /></a></td></tr>
168 </table>
169 <!-- sponsors -->
170 <!-- skip-docs -->
171
172 ## License
173
174 BSD licensed. See the LICENSE file for details.