micro/config/options/options.go

74 lines
1.5 KiB
Go
Raw Normal View History

2019-06-07 11:18:08 +01:00
// Package options provides a way to initialise options
2019-06-06 17:54:30 +01:00
package options
2019-06-06 11:32:38 +01:00
import (
"sync"
)
2019-06-06 17:54:30 +01:00
// Options is used for initialisation
type Options interface {
// Initialise options
Init(...Option) error
// Options returns the current options
2019-06-06 21:45:28 +01:00
Values() *Values
2019-06-06 17:54:30 +01:00
// The name for who these options exist
String() string
}
2019-06-06 11:46:13 +01:00
// Values holds the set of option values and protects them
type Values struct {
2019-06-06 11:32:38 +01:00
sync.RWMutex
values map[interface{}]interface{}
}
// Option gives access to options
2019-06-06 11:46:13 +01:00
type Option func(o *Values) error
2019-06-06 11:32:38 +01:00
// Get a value from options
2019-06-06 11:46:13 +01:00
func (o *Values) Get(k interface{}) (interface{}, bool) {
2019-06-06 11:32:38 +01:00
o.RLock()
defer o.RUnlock()
v, ok := o.values[k]
return v, ok
}
// Set a value in the options
2019-06-06 11:46:13 +01:00
func (o *Values) Set(k, v interface{}) error {
2019-06-06 11:32:38 +01:00
o.Lock()
defer o.Unlock()
if o.values == nil {
o.values = map[interface{}]interface{}{}
}
o.values[k] = v
return nil
}
// SetOption executes an option
2019-06-06 11:46:13 +01:00
func (o *Values) Option(op Option) error {
2019-06-06 11:32:38 +01:00
return op(o)
}
// WithValue allows you to set any value within the options
func WithValue(k, v interface{}) Option {
2019-06-06 11:46:13 +01:00
return func(o *Values) error {
return o.Set(k, v)
2019-06-06 11:32:38 +01:00
}
}
// WithOption gives you the ability to create an option that accesses values
func WithOption(o Option) Option {
return o
}
// String sets the string
2019-06-06 21:45:28 +01:00
func WithString(s string) Option {
2019-06-06 11:32:38 +01:00
return WithValue(stringKey{}, s)
}
2019-06-06 17:54:30 +01:00
// NewOptions returns a new initialiser
func NewOptions(opts ...Option) Options {
o := new(defaultOptions)
o.Init(opts...)
return o
}