2017-01-12 16:47:10 -05:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
2017-02-13 16:11:36 -05:00
|
|
|
// ConfigCreator is a function to create an object by a config.
|
|
|
|
type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error)
|
2017-01-12 16:47:10 -05:00
|
|
|
|
|
|
|
var (
|
2017-02-13 16:11:36 -05:00
|
|
|
typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
|
2017-01-12 16:47:10 -05:00
|
|
|
)
|
|
|
|
|
2017-02-13 16:11:36 -05:00
|
|
|
// RegisterConfig registers a global config creator. The config can be nil but must have a type.
|
|
|
|
func RegisterConfig(config interface{}, configCreator ConfigCreator) error {
|
2017-01-12 16:47:10 -05:00
|
|
|
configType := reflect.TypeOf(config)
|
|
|
|
if _, found := typeCreatorRegistry[configType]; found {
|
2017-04-08 19:43:25 -04:00
|
|
|
return newError("Common: " + configType.Name() + " is already registered.")
|
2017-01-12 16:47:10 -05:00
|
|
|
}
|
|
|
|
typeCreatorRegistry[configType] = configCreator
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-02-13 16:11:36 -05:00
|
|
|
// CreateObject creates an object by its config. The config type must be registered through RegisterConfig().
|
2017-01-12 16:47:10 -05:00
|
|
|
func CreateObject(ctx context.Context, config interface{}) (interface{}, error) {
|
|
|
|
configType := reflect.TypeOf(config)
|
|
|
|
creator, found := typeCreatorRegistry[configType]
|
|
|
|
if !found {
|
2017-04-08 19:43:25 -04:00
|
|
|
return nil, newError("Common: " + configType.String() + " is not registered.")
|
2017-01-12 16:47:10 -05:00
|
|
|
}
|
|
|
|
return creator(ctx, config)
|
|
|
|
}
|