1+ package main
2+
3+ import (
4+ "context"
5+ "errors" // Added missing import
6+ "log"
7+
8+ "github.com/samuelarogbonlo/dynconf/pkg/dynconf"
9+ )
10+
11+ type FeatureConfig struct {
12+ Enabled bool `json:"enabled"`
13+ Percentage float64 `json:"percentage"`
14+ MaxRequests int `json:"max_requests"`
15+ }
16+
17+ func main () {
18+ ctx := context .Background ()
19+
20+ cfg := dynconf .New [FeatureConfig ]()
21+
22+ // Create validation function
23+ validateFunc := func (old , new FeatureConfig ) error {
24+ return validateFeature (new )
25+ }
26+
27+ // Configure with validation
28+ cfg = dynconf .New [FeatureConfig ](
29+ dynconf.WithValidation [FeatureConfig ](validateFunc ),
30+ dynconf.WithRollback [FeatureConfig ](true ),
31+ )
32+
33+ // Subscribe to changes instead of Watch
34+ changes , cleanup := cfg .Subscribe (ctx )
35+ defer cleanup ()
36+
37+ // Create a rollout checker
38+ isEnabled := func (cfg FeatureConfig ) bool {
39+ return cfg .Enabled && cfg .Percentage > 0
40+ }
41+
42+ go func () {
43+ for newCfg := range changes {
44+ if isEnabled (newCfg ) {
45+ log .Printf ("Applying feature config: %+v" , newCfg )
46+ if err := applyFeature (newCfg ); err != nil {
47+ log .Printf ("Error applying feature: %v" , err )
48+ }
49+ }
50+ }
51+ }()
52+
53+ select {}
54+ }
55+
56+ func validateFeature (cfg FeatureConfig ) error {
57+ if cfg .Percentage < 0 || cfg .Percentage > 100 {
58+ return errors .New ("percentage must be between 0 and 100" )
59+ }
60+ if cfg .MaxRequests < 0 {
61+ return errors .New ("max requests must be non-negative" )
62+ }
63+ return nil
64+ }
65+
66+ func applyFeature (cfg FeatureConfig ) error {
67+ // Implementation to apply feature configuration
68+ return nil
69+ }
0 commit comments