gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/config/options/options.go (about) 1 // Package options provides a way to initialise options 2 package options 3 4 import ( 5 "log" 6 "sync" 7 ) 8 9 // Options is used for initialisation 10 type Options interface { 11 // Initialise options 12 Init(...Option) error 13 // Options returns the current options 14 Values() *Values 15 // The name for who these options exist 16 String() string 17 } 18 19 // Values holds the set of option values and protects them 20 type Values struct { 21 sync.RWMutex 22 values map[interface{}]interface{} 23 } 24 25 // Option gives access to options 26 type Option func(o *Values) error 27 28 // Get a value from options 29 func (o *Values) Get(k interface{}) (interface{}, bool) { 30 o.RLock() 31 defer o.RUnlock() 32 v, ok := o.values[k] 33 return v, ok 34 } 35 36 // Set a value in the options 37 func (o *Values) Set(k, v interface{}) error { 38 o.Lock() 39 defer o.Unlock() 40 if o.values == nil { 41 o.values = map[interface{}]interface{}{} 42 } 43 o.values[k] = v 44 return nil 45 } 46 47 // SetOption executes an option 48 func (o *Values) Option(op Option) error { 49 return op(o) 50 } 51 52 // WithValue allows you to set any value within the options 53 func WithValue(k, v interface{}) Option { 54 return func(o *Values) error { 55 return o.Set(k, v) 56 } 57 } 58 59 // WithOption gives you the ability to create an option that accesses values 60 func WithOption(o Option) Option { 61 return o 62 } 63 64 // String sets the string 65 func WithString(s string) Option { 66 return WithValue(stringKey{}, s) 67 } 68 69 // NewOptions returns a new initialiser 70 func NewOptions(opts ...Option) Options { 71 o := new(defaultOptions) 72 if err := o.Init(opts...); err != nil { 73 log.Fatal(err) 74 } 75 return o 76 }