github.com/xraypb/xray-core@v1.6.6/common/type.go (about) 1 package common 2 3 import ( 4 "context" 5 "reflect" 6 ) 7 8 // ConfigCreator is a function to create an object by a config. 9 type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error) 10 11 var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator) 12 13 // RegisterConfig registers a global config creator. The config can be nil but must have a type. 14 func RegisterConfig(config interface{}, configCreator ConfigCreator) error { 15 configType := reflect.TypeOf(config) 16 if _, found := typeCreatorRegistry[configType]; found { 17 return newError(configType.Name() + " is already registered").AtError() 18 } 19 typeCreatorRegistry[configType] = configCreator 20 return nil 21 } 22 23 // CreateObject creates an object by its config. The config type must be registered through RegisterConfig(). 24 func CreateObject(ctx context.Context, config interface{}) (interface{}, error) { 25 configType := reflect.TypeOf(config) 26 creator, found := typeCreatorRegistry[configType] 27 if !found { 28 return nil, newError(configType.String() + " is not registered").AtError() 29 } 30 return creator(ctx, config) 31 }