/
doc_test.go
97 lines (85 loc) · 2.52 KB
/
doc_test.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
89
90
91
92
93
94
95
96
97
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package confmap_test
import (
"fmt"
"slices"
"time"
"go.opentelemetry.io/collector/confmap"
)
type DiskScrape struct {
Disk string `mapstructure:"disk"`
Scrape time.Duration `mapstructure:"scrape"`
}
// We can annotate a struct with mapstructure field annotations.
func Example_simpleUnmarshaling() {
conf := confmap.NewFromStringMap(map[string]any{
"disk": "c",
"scrape": "5s",
})
scrapeInfo := &DiskScrape{}
if err := conf.Unmarshal(scrapeInfo); err != nil {
panic(err)
}
fmt.Printf("Configuration contains the following:\nDisk: %q\nScrape: %s\n", scrapeInfo.Disk, scrapeInfo.Scrape)
//Output: Configuration contains the following:
// Disk: "c"
// Scrape: 5s
}
type CPUScrape struct {
Enabled bool `mapstructure:"enabled"`
}
type ComputerScrape struct {
DiskScrape `mapstructure:",squash"`
CPUScrape `mapstructure:",squash"`
}
// We can unmarshal embedded structs with mapstructure field annotations.
func Example_embeddedUnmarshaling() {
conf := confmap.NewFromStringMap(map[string]any{
"disk": "c",
"scrape": "5s",
"enabled": true,
})
scrapeInfo := &ComputerScrape{}
if err := conf.Unmarshal(scrapeInfo); err != nil {
panic(err)
}
fmt.Printf("Configuration contains the following:\nDisk: %q\nScrape: %s\nEnabled: %v\n", scrapeInfo.Disk, scrapeInfo.Scrape, scrapeInfo.Enabled)
//Output: Configuration contains the following:
// Disk: "c"
// Scrape: 5s
// Enabled: true
}
type NetworkScrape struct {
Enabled bool `mapstructure:"enabled"`
Networks []string `mapstructure:"networks"`
Wifi bool `mapstructure:"wifi"`
}
func (n *NetworkScrape) Unmarshal(c *confmap.Conf) error {
if err := c.Unmarshal(n, confmap.WithIgnoreUnused()); err != nil {
return err
}
if slices.Contains(n.Networks, "wlan0") {
n.Wifi = true
}
return nil
}
type RouterScrape struct {
NetworkScrape `mapstructure:",squash"`
}
// We can unmarshal an embedded struct with a custom `Unmarshal` method.
func Example_embeddedManualUnmarshaling() {
conf := confmap.NewFromStringMap(map[string]any{
"networks": []string{"eth0", "eth1", "wlan0"},
"enabled": true,
})
scrapeInfo := &RouterScrape{}
if err := conf.Unmarshal(scrapeInfo); err != nil {
panic(err)
}
fmt.Printf("Configuration contains the following:\nNetworks: %q\nWifi: %v\nEnabled: %v\n", scrapeInfo.Networks, scrapeInfo.Wifi, scrapeInfo.Enabled)
//Output: Configuration contains the following:
// Networks: ["eth0" "eth1" "wlan0"]
// Wifi: true
// Enabled: true
}