@@ -17,6 +17,7 @@ import (
1717 "context"
1818 "fmt"
1919
20+ "github.com/mitchellh/mapstructure"
2021 "github.com/prometheus/client_golang/prometheus"
2122 "go.opentelemetry.io/collector/component"
2223 "go.opentelemetry.io/collector/consumer"
@@ -34,11 +35,12 @@ type ExporterInitializer interface {
3435 Shutdown (ctx context.Context ) error
3536}
3637
37- // ConfigUnmarshaler is the interface for unmarshaling exporter-specific configuration.
38+ // ConfigUnmarshaler is the interface for struct-based configuration
39+ // with automatic validation using mapstructure and struct tags.
3840type ConfigUnmarshaler interface {
39- // UnmarshalExporterConfig parses the exporter-specific configuration
40- // from the raw map into a Config instance .
41- UnmarshalExporterConfig ( data map [ string ] interface {}) ( Config , error )
41+ // GetConfigStruct returns a pointer to the config struct that mapstructure
42+ // will populate. The struct should have appropriate mapstructure tags .
43+ GetConfigStruct () Config
4244}
4345
4446// FactoryOption is a function that configures a Factory.
@@ -130,12 +132,27 @@ func createMetricsReceiver(
130132 return nil , fmt .Errorf ("invalid config type: %T" , cfg )
131133 }
132134
133- // Unmarshal the exporter-specific config
135+ // Unmarshal the exporter-specific config using mapstructure
134136 if len (receiverCfg .ExporterConfig ) > 0 {
135- exporterCfg , err := unmarshaler .UnmarshalExporterConfig (receiverCfg .ExporterConfig )
137+ // Get the config struct from the unmarshaler
138+ exporterCfg := unmarshaler .GetConfigStruct ()
139+
140+ // Configure mapstructure for strict validation
141+ decoder , err := mapstructure .NewDecoder (& mapstructure.DecoderConfig {
142+ Result : exporterCfg ,
143+ ErrorUnused : true , // Reject unknown fields
144+ WeaklyTypedInput : false , // Strict type checking
145+ TagName : "mapstructure" ,
146+ })
136147 if err != nil {
137- return nil , fmt .Errorf ("failed to unmarshal exporter config : %w" , err )
148+ return nil , fmt .Errorf ("failed to create decoder : %w" , err )
138149 }
150+
151+ // Decode with automatic validation
152+ if err = decoder .Decode (receiverCfg .ExporterConfig ); err != nil {
153+ return nil , fmt .Errorf ("configuration validation failed: %w" , err )
154+ }
155+
139156 receiverCfg .SetExporterConfig (exporterCfg )
140157 }
141158
0 commit comments