github.com/thanos-io/thanos@v0.32.5/internal/cortex/util/flagext/cidr.go (about) 1 // Copyright (c) The Cortex Authors. 2 // Licensed under the Apache License 2.0. 3 4 package flagext 5 6 import ( 7 "net" 8 "strings" 9 10 "github.com/pkg/errors" 11 ) 12 13 // CIDR is a network CIDR. 14 type CIDR struct { 15 Value *net.IPNet 16 } 17 18 // String implements flag.Value. 19 func (c CIDR) String() string { 20 if c.Value == nil { 21 return "" 22 } 23 return c.Value.String() 24 } 25 26 // Set implements flag.Value. 27 func (c *CIDR) Set(s string) error { 28 _, value, err := net.ParseCIDR(s) 29 if err != nil { 30 return err 31 } 32 c.Value = value 33 return nil 34 } 35 36 // CIDRSliceCSV is a slice of CIDRs that is parsed from a comma-separated string. 37 // It implements flag.Value and yaml Marshalers. 38 type CIDRSliceCSV []CIDR 39 40 // String implements flag.Value 41 func (c CIDRSliceCSV) String() string { 42 values := make([]string, 0, len(c)) 43 for _, cidr := range c { 44 values = append(values, cidr.String()) 45 } 46 47 return strings.Join(values, ",") 48 } 49 50 // Set implements flag.Value 51 func (c *CIDRSliceCSV) Set(s string) error { 52 parts := strings.Split(s, ",") 53 54 for _, part := range parts { 55 cidr := &CIDR{} 56 if err := cidr.Set(part); err != nil { 57 return errors.Wrapf(err, "cidr: %s", part) 58 } 59 60 *c = append(*c, *cidr) 61 } 62 63 return nil 64 } 65 66 // UnmarshalYAML implements yaml.Unmarshaler. 67 func (c *CIDRSliceCSV) UnmarshalYAML(unmarshal func(interface{}) error) error { 68 var s string 69 if err := unmarshal(&s); err != nil { 70 return err 71 } 72 73 // An empty string means no CIDRs has been configured. 74 if s == "" { 75 *c = nil 76 return nil 77 } 78 79 return c.Set(s) 80 } 81 82 // MarshalYAML implements yaml.Marshaler. 83 func (c CIDRSliceCSV) MarshalYAML() (interface{}, error) { 84 return c.String(), nil 85 }