github.com/zhyoulun/cilium@v1.6.12/pkg/option/map_options.go (about) 1 // Copyright 2016-2017 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package option 16 17 import ( 18 "fmt" 19 "strings" 20 ) 21 22 // Validator returns a validated string along with a possible error. 23 type Validator func(val string) (string, error) 24 25 // MapOptions holds a map of values and a validation function. 26 type MapOptions struct { 27 vals map[string]string 28 validator Validator 29 } 30 31 // NamedMapOptions is a MapOptions struct with a configuration name. 32 // This struct is useful to keep reference to the assigned 33 // field name in the internal configuration struct. 34 type NamedMapOptions struct { 35 name string 36 MapOptions 37 } 38 39 // NewNamedMapOptions creates a reference to a new NamedMapOpts struct. 40 func NewNamedMapOptions(name string, values *map[string]string, validator Validator) *NamedMapOptions { 41 return &NamedMapOptions{ 42 name: name, 43 MapOptions: *NewMapOpts(*values, validator), 44 } 45 } 46 47 // NewMapOpts creates a new MapOpts with the specified map of values and an 48 // optional validator. 49 func NewMapOpts(values map[string]string, validator Validator) *MapOptions { 50 if values == nil { 51 values = make(map[string]string) 52 } 53 return &MapOptions{ 54 vals: values, 55 validator: validator, 56 } 57 } 58 59 func (opts *MapOptions) String() string { 60 return fmt.Sprintf("%v", opts.vals) 61 } 62 63 // Type returns a string name for this Option type 64 func (opts *MapOptions) Type() string { 65 return "map" 66 } 67 68 // Set validates, if needed, the input value and adds it to the internal map, 69 // by splitting on '='. 70 func (opts *MapOptions) Set(value string) error { 71 if opts.validator != nil { 72 v, err := opts.validator(value) 73 if err != nil { 74 return err 75 } 76 value = v 77 } 78 vals := strings.SplitN(value, "=", 2) 79 if len(vals) == 1 { 80 (opts.vals)[vals[0]] = "" 81 } else { 82 (opts.vals)[vals[0]] = vals[1] 83 } 84 return nil 85 }