-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_test.go
More file actions
347 lines (286 loc) · 8.83 KB
/
example_test.go
File metadata and controls
347 lines (286 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !integration
package binding_test
import (
"bytes"
"fmt"
"mime/multipart"
"net/url"
"rivaas.dev/binding"
)
// ExampleQuery demonstrates basic binding from query parameters using generic API.
func ExampleQuery() {
type Params struct {
Name string `query:"name"`
Age int `query:"age"`
Email string `query:"email"`
}
values := url.Values{}
values.Set("name", "Alice")
values.Set("age", "30")
values.Set("email", "alice@example.com")
params, err := binding.Query[Params](values)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Name: %s, Age: %d, Email: %s\n", params.Name, params.Age, params.Email)
// Output: Name: Alice, Age: 30, Email: alice@example.com
}
// ExampleQueryTo demonstrates non-generic query binding.
func ExampleQueryTo() {
type Params struct {
Name string `query:"name"`
Age int `query:"age"`
Email string `query:"email"`
}
values := url.Values{}
values.Set("name", "Bob")
values.Set("age", "25")
values.Set("email", "bob@example.com")
var params Params
err := binding.QueryTo(values, ¶ms)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Name: %s, Age: %d, Email: %s\n", params.Name, params.Age, params.Email)
// Output: Name: Bob, Age: 25, Email: bob@example.com
}
// ExamplePath demonstrates binding from path parameters.
func ExamplePath() {
type Params struct {
ID int `path:"id"`
Slug string `path:"slug"`
}
pathParams := map[string]string{
"id": "123",
"slug": "hello-world",
}
params, err := binding.Path[Params](pathParams)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("ID: %d, Slug: %s\n", params.ID, params.Slug)
// Output: ID: 123, Slug: hello-world
}
// ExampleJSON demonstrates binding from JSON body.
func ExampleJSON() {
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
body := []byte(`{"name": "Charlie", "email": "charlie@example.com", "age": 35}`)
user, err := binding.JSON[User](body)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Name: %s, Email: %s, Age: %d\n", user.Name, user.Email, user.Age)
// Output: Name: Charlie, Email: charlie@example.com, Age: 35
}
// ExampleBind demonstrates multi-source binding.
func ExampleBind() {
type Request struct {
// From path parameters
UserID int `path:"user_id"`
// From query string
Page int `query:"page"`
Limit int `query:"limit"`
}
pathParams := map[string]string{"user_id": "456"}
query := url.Values{}
query.Set("page", "2")
query.Set("limit", "20")
req, err := binding.Bind[Request](
binding.FromPath(pathParams),
binding.FromQuery(query),
)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("UserID: %d, Page: %d, Limit: %d\n", req.UserID, req.Page, req.Limit)
// Output: UserID: 456, Page: 2, Limit: 20
}
// ExampleBindTo demonstrates non-generic multi-source binding.
func ExampleBindTo() {
type Request struct {
UserID int `path:"user_id"`
Page int `query:"page"`
}
pathParams := map[string]string{"user_id": "789"}
query := url.Values{}
query.Set("page", "3")
var req Request
err := binding.BindTo(&req,
binding.FromPath(pathParams),
binding.FromQuery(query),
)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("UserID: %d, Page: %d\n", req.UserID, req.Page)
// Output: UserID: 789, Page: 3
}
// ExampleQuery_withDefaults demonstrates binding with default values.
func ExampleQuery_withDefaults() {
type Config struct {
Port int `query:"port" default:"8080"`
Host string `query:"host" default:"localhost"`
Debug bool `query:"debug" default:"false"`
LogLevel string `query:"log_level" default:"info"`
}
// Empty query string - defaults will be applied
values := url.Values{}
config, err := binding.Query[Config](values)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Port: %d, Host: %s, Debug: %v, LogLevel: %s\n", config.Port, config.Host, config.Debug, config.LogLevel)
// Output: Port: 8080, Host: localhost, Debug: false, LogLevel: info
}
// ExampleQuery_withOptions demonstrates binding with custom options.
func ExampleQuery_withOptions() {
type Params struct {
Tags []string `query:"tags"`
}
values := url.Values{}
values.Set("tags", "go,rust,python")
// Use CSV mode for comma-separated values
params, err := binding.Query[Params](values,
binding.WithSliceMode(binding.SliceCSV),
)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Tags: %v\n", params.Tags)
// Output: Tags: [go rust python]
}
// ExampleMustNew demonstrates creating a reusable Binder.
func ExampleMustNew() {
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
// Create a configured binder
binder := binding.MustNew(
binding.WithMaxDepth(16),
)
body := []byte(`{"name": "Diana", "email": "diana@example.com"}`)
// Use generic helper function with binder
user, err := binding.JSONWith[User](binder, body)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Name: %s, Email: %s\n", user.Name, user.Email)
// Output: Name: Diana, Email: diana@example.com
}
// ExampleJSON_withUnknownFields demonstrates strict JSON binding.
func ExampleJSON_withUnknownFields() {
type User struct {
Name string `json:"name"`
}
// JSON with unknown field "extra"
body := []byte(`{"name": "Eve", "extra": "ignored"}`)
// Default: unknown fields are ignored
user, err := binding.JSON[User](body)
if err != nil {
_, _ = fmt.Printf("Error: %v\n", err)
return
}
_, _ = fmt.Printf("Name: %s\n", user.Name)
// Output: Name: Eve
}
// ExampleHasStructTag demonstrates checking if a struct has specific tags.
func ExampleHasStructTag() {
type UserRequest struct {
ID int `path:"id"`
Name string `query:"name"`
Auth string `header:"Authorization"`
}
// Check at compile time which sources a struct uses
var req UserRequest
_ = req // Use the variable
// In real code, you'd use reflect.TypeOf:
// typ := reflect.TypeOf((*UserRequest)(nil)).Elem()
// hasPath := binding.HasStructTag(typ, binding.TagPath)
_, _ = fmt.Printf("UserRequest has multiple source tags\n")
// Output: UserRequest has multiple source tags
}
// ExampleMultipart demonstrates binding multipart form data with file uploads.
func ExampleMultipart() {
// Simulate a multipart form with file upload and JSON data
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add a file upload
fw, err := writer.CreateFormFile("avatar", "photo.jpg")
if err != nil {
panic(err)
}
if _, writeErr := fw.Write([]byte("image data")); writeErr != nil {
panic(writeErr)
}
// Add form fields
if writeErr := writer.WriteField("username", "alice"); writeErr != nil {
panic(writeErr)
}
if writeErr := writer.WriteField("email", "alice@example.com"); writeErr != nil {
panic(writeErr)
}
// Add JSON in a form field (automatically parsed)
if writeErr := writer.WriteField("settings", `{"theme":"dark","notifications":true}`); writeErr != nil {
panic(writeErr)
}
if closeErr := writer.Close(); closeErr != nil {
panic(closeErr)
}
// Parse the multipart form
boundary := writer.FormDataContentType()[len("multipart/form-data; boundary="):]
mr := multipart.NewReader(bytes.NewReader(body.Bytes()), boundary)
form, err := mr.ReadForm(32 << 20)
if err != nil {
panic(err)
}
// Define request struct
type Settings struct {
Theme string `json:"theme"`
Notifications bool `json:"notifications"`
}
type Request struct {
Avatar *binding.File `form:"avatar"`
Username string `form:"username"`
Email string `form:"email"`
Settings Settings `form:"settings"` // JSON auto-parsed
}
// Bind multipart form to struct
req, err := binding.Multipart[Request](form)
if err != nil {
panic(err)
}
fmt.Printf("User: %s <%s>\n", req.Username, req.Email)
fmt.Printf("Avatar: %s (%d bytes)\n", req.Avatar.Name, req.Avatar.Size)
fmt.Printf("Settings: theme=%s, notifications=%t\n", req.Settings.Theme, req.Settings.Notifications)
// Output:
// User: alice <alice@example.com>
// Avatar: photo.jpg (10 bytes)
// Settings: theme=dark, notifications=true
}