Created
June 16, 2016 07:37
-
-
Save nanoninja/6a9e73cd9a368721a488da7827c17b93 to your computer and use it in GitHub Desktop.
Service Container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package service | |
import ( | |
"fmt" | |
"sync" | |
) | |
type key int | |
type Service func() interface{} | |
var ( | |
container = make(map[interface{}]Service) | |
mutex sync.RWMutex | |
) | |
func All() map[interface{}]interface{} { | |
mutex.RLock() | |
data := make(map[interface{}]interface{}) | |
for key, service := range container { | |
data[key] = service() | |
} | |
mutex.RUnlock() | |
return data | |
} | |
func Clear() { | |
mutex.Lock() | |
container = make(map[interface{}]Service) | |
mutex.Unlock() | |
} | |
func Get(key interface{}) interface{} { | |
var value interface{} | |
mutex.RLock() | |
if service, ok := container[key]; ok { | |
value = service() | |
} | |
mutex.RUnlock() | |
return value | |
} | |
func Has(key interface{}) bool { | |
mutex.RLock() | |
_, ok := container[key] | |
mutex.RUnlock() | |
return ok | |
} | |
func Len() int { | |
mutex.RLock() | |
count := len(container) | |
mutex.RUnlock() | |
return count | |
} | |
func Register(key interface{}, fn Service) error { | |
var err error = nil | |
mutex.Lock() | |
if _, ok := container[key]; ok { | |
err = fmt.Errorf("Service %v is already exist", key) | |
} else { | |
container[key] = fn | |
} | |
mutex.Unlock() | |
return err | |
} | |
func Set(key interface{}, fn Service) { | |
mutex.Lock() | |
container[key] = fn | |
mutex.Unlock() | |
} | |
func Unregister(key interface{}) { | |
mutex.Lock() | |
delete(container, key) | |
mutex.Unlock() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment