-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples_test.go
More file actions
237 lines (200 loc) · 5.21 KB
/
examples_test.go
File metadata and controls
237 lines (200 loc) · 5.21 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
package structwalker_test
import (
"fmt"
"strings"
"github.com/rjp2525/structwalker"
)
func ExampleWalker_basicUsage() {
type User struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"email"`
Age int `json:"age" validate:"min=0"`
}
w := structwalker.New()
w.Handle("json", func(ctx structwalker.FieldContext) error {
fmt.Printf("json field: %s -> %s\n", ctx.Path, ctx.Tag.Name)
return nil
})
w.Handle("validate", func(ctx structwalker.FieldContext) error {
fmt.Printf("validate: %s rule=%s\n", ctx.Path, ctx.Tag.Name)
return nil
})
user := &User{Name: "Alice", Email: "alice@example.com", Age: 30}
if err := w.Walk(user); err != nil {
fmt.Println("error:", err)
}
// Output:
// json field: Name -> name
// validate: Name rule=required
// json field: Email -> email
// validate: Email rule=email
// json field: Age -> age
// validate: Age rule=min=0
}
func ExampleWalker_sensitiveDataMasking() {
type APIResponse struct {
UserID int `json:"user_id"`
Email string `json:"email" mask:"redact"`
SSN string `json:"ssn" mask:"redact"`
PublicKey string `json:"public_key"`
}
w := structwalker.New()
w.Handle("mask", func(ctx structwalker.FieldContext) error {
if ctx.Tag.Name == "redact" {
return ctx.SetValue("***REDACTED***")
}
return nil
})
resp := &APIResponse{
UserID: 123,
Email: "alice@example.com",
SSN: "123-45-6789",
PublicKey: "ssh-rsa AAAA...",
}
if err := w.Walk(resp); err != nil {
fmt.Println("error:", err)
}
fmt.Println("Email:", resp.Email)
fmt.Println("SSN:", resp.SSN)
fmt.Println("PublicKey:", resp.PublicKey)
// Output:
// Email: ***REDACTED***
// SSN: ***REDACTED***
// PublicKey: ssh-rsa AAAA...
}
func ExampleWalker_nestedStructs() {
type Address struct {
Street string `json:"street"`
City string `json:"city"`
}
type User struct {
Name string `json:"name"`
Address Address `json:"address"`
}
w := structwalker.New()
w.Handle("json", func(ctx structwalker.FieldContext) error {
fmt.Printf("[depth=%d] %s\n", ctx.Depth, ctx.Path)
return nil
})
user := &User{Name: "Alice", Address: Address{Street: "123 Main St", City: "Springfield"}}
if err := w.Walk(user); err != nil {
fmt.Println("error:", err)
}
// Output:
// [depth=0] Name
// [depth=0] Address
// [depth=1] Address.Street
// [depth=1] Address.City
}
func ExampleWalker_handleAll() {
type Config struct {
Host string
Port int
Name string
}
var fields []string
w := structwalker.New()
w.HandleAll(func(ctx structwalker.FieldContext) error {
fields = append(fields, ctx.Field.Name)
return nil
})
if err := w.Walk(&Config{Host: "localhost", Port: 8080, Name: "app"}); err != nil {
fmt.Println("error:", err)
}
fmt.Println(strings.Join(fields, ", "))
// Output:
// Host, Port, Name
}
func ExampleWalker_skipChildren() {
type Secrets struct {
APIKey string `json:"api_key"`
Token string `json:"token"`
}
type Config struct {
Name string `json:"name"`
Secrets Secrets `json:"secrets" audit:"skip"`
}
w := structwalker.New()
w.Handle("json", func(ctx structwalker.FieldContext) error {
fmt.Printf("visited: %s\n", ctx.Path)
return nil
})
w.Handle("audit", func(ctx structwalker.FieldContext) error {
if ctx.Tag.Name == "skip" {
return structwalker.ErrSkipChildren
}
return nil
})
if err := w.Walk(&Config{Name: "myapp", Secrets: Secrets{APIKey: "key", Token: "tok"}}); err != nil {
fmt.Println("error:", err)
}
// Output:
// visited: Name
// visited: Secrets
}
func ExampleWalker_errorCollection() {
type Form struct {
Name string `validate:"required"`
Email string `validate:"required"`
Age int `validate:"required"`
}
w := structwalker.New(structwalker.WithErrorMode(structwalker.CollectErrors))
w.Handle("validate", func(ctx structwalker.FieldContext) error {
if ctx.Tag.Name == "required" && ctx.IsZero() {
return fmt.Errorf("field is required")
}
return nil
})
form := &Form{} // all zero values
err := w.Walk(form)
if err != nil {
fmt.Println("Validation failed:")
var multi *structwalker.MultiError
if ok := err.(*structwalker.MultiError); ok != nil {
multi = ok
for _, e := range multi.Errors {
fmt.Printf(" - %s: %s\n", e.Path, e.Err)
}
}
}
// Output:
// Validation failed:
// - Name: field is required
// - Email: field is required
// - Age: field is required
}
func ExampleWalker_sliceWalking() {
type Item struct {
Name string `tag:"name"`
}
type Cart struct {
Items []Item `tag:"items"`
}
w := structwalker.New(structwalker.WithSliceElements(true))
w.Handle("tag", func(ctx structwalker.FieldContext) error {
fmt.Printf("%s\n", ctx.Path)
return nil
})
cart := &Cart{Items: []Item{{Name: "Widget"}, {Name: "Gadget"}}}
if err := w.Walk(cart); err != nil {
fmt.Println("error:", err)
}
// Output:
// Items
// Items[0].Name
// Items[1].Name
}
func ExampleWithRecovery() {
type S struct {
Name string `tag:"name"`
}
w := structwalker.New()
w.Use(structwalker.WithRecovery())
w.Handle("tag", func(ctx structwalker.FieldContext) error {
panic("something went wrong")
})
err := w.Walk(&S{Name: "test"})
fmt.Println("recovered:", err != nil)
// Output:
// recovered: true
}