Skip to content

Commit dd48410

Browse files
Add documentation example for xconfmap (#5675) (#12832)
#### Description This PR introduces a simple testable examples to the package [confmap](/confmap/xconfmap). it's basically a copy of the documentation example on https://opentelemetry.io/docs/collector/building/receiver/#designing-and-validating-receiver-settings #### Issue: #5675 (comment) #### Testing the testable example was executed successfully ![image](https://github.com/user-attachments/assets/1b992f1a-fd69-452d-be46-288672710334) #### Documentation this testable example follows https://go.dev/blog/examples#larger-examples format and should be automatically added to `xconfmap` package documentation Co-authored-by: Pablo Baeyens <[email protected]> Co-authored-by: Pablo Baeyens <[email protected]>
1 parent 9dc5682 commit dd48410

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

confmap/xconfmap/example_test.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package xconfmap
5+
6+
import (
7+
"errors"
8+
"fmt"
9+
"time"
10+
)
11+
12+
// Config represents the receiver config settings within the collector's config.yaml
13+
type Config struct {
14+
Interval time.Duration `mapstructure:"interval"`
15+
NumberOfTraces int `mapstructure:"number_of_traces"`
16+
}
17+
18+
// Validate checks if the receiver configuration is valid
19+
// this function is automatically called by the collector when it loads the configurations
20+
// for a component
21+
func (cfg *Config) Validate() error {
22+
if cfg.Interval.Minutes() < 1 {
23+
return errors.New("when defined, the interval has to be set to at least 1 minute (1m)")
24+
}
25+
26+
if cfg.NumberOfTraces < 1 {
27+
return errors.New("number_of_traces must be greater or equal to 1")
28+
}
29+
return nil
30+
}
31+
32+
// Example usage validated configuration
33+
func Example() {
34+
// invalid number of traces
35+
myCfg := Config{
36+
Interval: time.Minute,
37+
NumberOfTraces: 0,
38+
}
39+
err := myCfg.Validate()
40+
fmt.Println(err)
41+
42+
// invalid interval
43+
myCfg = Config{
44+
Interval: time.Second,
45+
NumberOfTraces: 1,
46+
}
47+
err = myCfg.Validate()
48+
fmt.Println(err)
49+
50+
// valid config
51+
myCfg = Config{
52+
Interval: time.Minute,
53+
NumberOfTraces: 1,
54+
}
55+
err = myCfg.Validate()
56+
fmt.Println(err)
57+
58+
// Output:
59+
// number_of_traces must be greater or equal to 1
60+
// when defined, the interval has to be set to at least 1 minute (1m)
61+
// <nil>
62+
}

0 commit comments

Comments
 (0)