-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (79 loc) · 1.99 KB
/
main.go
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
package main
import (
"errors"
"log"
"os"
"github.com/nikoksr/konfetty"
"github.com/nikoksr/konfetty/examples"
)
type PizzaConfig struct {
Size string
Crust string
Sauce string
Cheese string
Toppings []string
ExtraCheese bool
}
type OrderConfig struct {
Pizza PizzaConfig
Quantity int
Delivery bool
Address string
}
func main() {
// Create a basic pizza order. Typically, you'd populate this from a config file or some other source.
cfg := &OrderConfig{
Pizza: PizzaConfig{
Size: "medium",
Crust: "thin",
},
Quantity: 1,
Address: "A-123, 4th Street, New York",
}
// Use konfetty to process the config
cfg, err := konfetty.FromStruct(cfg).
WithDefaults(
OrderConfig{
Pizza: PizzaConfig{
Sauce: "tomato",
Cheese: "mozzarella",
Toppings: []string{"mushrooms"},
ExtraCheese: false,
},
},
).
WithTransformer(func(c *OrderConfig) {
if c.Address != "" {
c.Delivery = true
}
}).
WithValidator(func(c *OrderConfig) error {
if c.Delivery && c.Address == "" {
return errors.New("delivery address is required for delivery orders")
}
return nil
}).
Build()
if err != nil {
log.Fatalf("Error processing pizza order: %v", err)
}
// Use the final config as needed...
examples.PrettyPrint(os.Stdout, cfg)
// The final config would look like this:
//
// {
// "Pizza": {
// "Size": "medium", // Kept original value
// "Crust": "thin", // Kept original value
// "Sauce": "tomato", // Applied from defaults
// "Cheese": "mozzarella", // Applied from defaults
// "Toppings": [
// "mushrooms"
// ], // Applied from defaults
// "ExtraCheese": false // Applied from defaults
// },
// "Quantity": 1, // Kept original value
// "Delivery": true, // Applied from transformer
// "Address": "A-123, 4th Street, New York" // Kept original value
// }
}