1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-02-20 23:47:21 -05:00

36 lines
1.2 KiB
Go
Raw Normal View History

2017-01-12 22:47:10 +01:00
package common
import (
"context"
"reflect"
2021-09-05 00:47:15 +01:00
"github.com/v2fly/v2ray-core/v5/common/registry"
2017-01-12 22:47:10 +01:00
)
2017-02-13 22:11:36 +01: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 22:47:10 +01:00
2021-05-20 05:28:52 +08:00
var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
2017-01-12 22:47:10 +01:00
2017-02-13 22:11:36 +01: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 22:47:10 +01:00
configType := reflect.TypeOf(config)
if _, found := typeCreatorRegistry[configType]; found {
2017-04-09 15:04:04 +02:00
return newError(configType.Name() + " is already registered").AtError()
2017-01-12 22:47:10 +01:00
}
typeCreatorRegistry[configType] = configCreator
2021-09-05 00:47:15 +01:00
registry.RegisterImplementation(config, nil)
2017-01-12 22:47:10 +01:00
return nil
}
2017-02-13 22:11:36 +01:00
// CreateObject creates an object by its config. The config type must be registered through RegisterConfig().
2017-01-12 22:47:10 +01:00
func CreateObject(ctx context.Context, config interface{}) (interface{}, error) {
configType := reflect.TypeOf(config)
creator, found := typeCreatorRegistry[configType]
if !found {
2017-04-09 15:04:04 +02:00
return nil, newError(configType.String() + " is not registered").AtError()
2017-01-12 22:47:10 +01:00
}
return creator(ctx, config)
}