add init package

This commit is contained in:
Asim Aslam 2019-06-06 11:32:38 +01:00
parent 0f70281e28
commit ab7d036697
3 changed files with 120 additions and 0 deletions

44
init/default.go Normal file
View File

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

21
init/init.go Normal file
View File

@ -0,0 +1,21 @@
// Package init is an interface for initialising options
package init
// Init is used for initialisation
type Init 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
}
// NewInit returns a new initialiser
func NewInit(opts ...Option) Init {
i := new(defaultInit)
i.Init(opts...)
return i
}

55
init/options.go Normal file
View File

@ -0,0 +1,55 @@
package init
import (
"sync"
)
// Options holds the set of option values and protects them
type Options struct {
sync.RWMutex
values map[interface{}]interface{}
}
// Option gives access to options
type Option func(o *Options) error
// Get a value from options
func (o *Options) Value(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 *Options) SetValue(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 *Options) SetOption(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 *Options) error {
return o.SetValue(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)
}