move init to options

This commit is contained in:
Asim Aslam
2019-06-06 17:54:30 +01:00
parent c60b5a45bb
commit 64459c54a1
3 changed files with 21 additions and 23 deletions

41
options/default.go Normal file
View File

@@ -0,0 +1,41 @@
package options
type defaultOptions struct {
opts *Values
}
type stringKey struct{}
func (d *defaultOptions) Init(opts ...Option) error {
if d.opts == nil {
d.opts = new(Values)
}
for _, o := range opts {
if err := d.opts.Option(o); err != nil {
return err
}
}
return nil
}
func (d *defaultOptions) Options() Options {
return d
}
func (d *defaultOptions) Value(k interface{}) (interface{}, bool) {
if d.opts == nil {
d.opts = new(Values)
}
return d.opts.Get(k)
}
func (d *defaultOptions) String() string {
if d.opts == nil {
d.opts = new(Values)
}
n, ok := d.opts.Get(stringKey{})
if ok {
return n.(string)
}
return "Values"
}

74
options/options.go Normal file
View File

@@ -0,0 +1,74 @@
package options
import (
"sync"
)
// Options is used for initialisation
type Options interface {
// Initialise options
Init(...Option) error
// Options returns the current options
Options() Options
// Value returns an option value
Value(k interface{}) (interface{}, bool)
// The name for who these options exist
String() string
}
// Values holds the set of option values and protects them
type Values struct {
sync.RWMutex
values map[interface{}]interface{}
}
// Option gives access to options
type Option func(o *Values) error
// Get a value from options
func (o *Values) Get(k interface{}) (interface{}, bool) {
o.RLock()
defer o.RUnlock()
v, ok := o.values[k]
return v, ok
}
// Set a value in the options
func (o *Values) Set(k, v interface{}) error {
o.Lock()
defer o.Unlock()
if o.values == nil {
o.values = map[interface{}]interface{}{}
}
o.values[k] = v
return nil
}
// SetOption executes an option
func (o *Values) Option(op Option) error {
return op(o)
}
// WithValue allows you to set any value within the options
func WithValue(k, v interface{}) Option {
return func(o *Values) error {
return o.Set(k, v)
}
}
// WithOption gives you the ability to create an option that accesses values
func WithOption(o Option) Option {
return o
}
// String sets the string
func String(s string) Option {
return WithValue(stringKey{}, s)
}
// NewOptions returns a new initialiser
func NewOptions(opts ...Option) Options {
o := new(defaultOptions)
o.Init(opts...)
return o
}