Skip to content

Instantly share code, notes, and snippets.

@nanoninja
Last active November 26, 2015 22:04
Show Gist options
  • Save nanoninja/75a23489b5e121fd7ee3 to your computer and use it in GitHub Desktop.
Save nanoninja/75a23489b5e121fd7ee3 to your computer and use it in GitHub Desktop.
Box of Services
// Copyright 2015 The Nanoninja Authors. All rights reserved.
package box
import "time"
// ServiceFunc registers the service function.
type ServiceFunc func(b *Box) interface{}
type Box struct {
name string
services map[string]ServiceFunc
}
// New allocates a new services box with the given name.
func New(name string) *Box {
return &Box{name, make(map[string]ServiceFunc)}
}
// Name returns the name of the box.
func (b Box) Name() string {
return b.name
}
// Wrap wrap a function service.
func (b *Box) Wrap(value interface{}) ServiceFunc {
return ServiceFunc(func(b *Box) interface{} {
return value
})
}
// Set sets a service of the box.
func (b *Box) Set(id string, fn ServiceFunc) {
b.services[id] = fn
}
// Get returns a value of service registered in the box.
func (b Box) Get(id string) interface{} {
if service, ok := b.services[id]; ok {
return service(&b)
}
return nil
}
func (b *Box) SetStr(id, value string) {
b.Set(id, b.Wrap(value))
}
func (b Box) GetStr(id string) string {
value, _ := b.Get(id).(string)
return value
}
func (b *Box) SetFlag(id string, value bool) {
b.Set(id, b.Wrap(value))
}
func (b Box) GetFlag(id string) bool {
value, _ := b.Get(id).(bool)
return value
}
func (b *Box) SetInt(id string, value int) {
b.Set(id, b.Wrap(value))
}
func (b Box) GetInt(id string) int {
value, _ := b.Get(id).(int)
return value
}
func (b *Box) SetUint64(id string, value uint64) {
b.Set(id, b.Wrap(value))
}
func (b Box) GetUint64(id string) uint64 {
value, ok := b.Get(id).(uint64)
return value
}
func (b *Box) SetFloat64(id string, value float64) {
b.Set(id, b.Wrap(value))
}
func (b Box) GetFloat64(id string) float64 {
value, _ := b.Get(id).(float64)
return value
}
func (b *Box) SetDuration(id string, value time.Duration) {
b.Set(id, b.Wrap(value))
}
func (b Box) GetDuration(id string) time.Duration {
value, _ := b.Get(id).(time.Duration)
return value
}
// Share provides a shared value
func (b Box) Share(fn ServiceFunc) ServiceFunc {
var service interface{}
return func(b *Box) interface{} {
if service == nil {
service = fn(b)
}
return service
}
}
// Remove removes a service of the box.
func (b *Box) Remove(id string) {
delete(b.services, id)
}
// Clear clears all the box.
func (b *Box) Clear() {
b.services = make(map[string]ServiceFunc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment