github.com/EagleQL/Xray-core@v1.4.3/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 (
    12  	typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
    13  )
    14  
    15  // RegisterConfig registers a global config creator. The config can be nil but must have a type.
    16  func RegisterConfig(config interface{}, configCreator ConfigCreator) error {
    17  	configType := reflect.TypeOf(config)
    18  	if _, found := typeCreatorRegistry[configType]; found {
    19  		return newError(configType.Name() + " is already registered").AtError()
    20  	}
    21  	typeCreatorRegistry[configType] = configCreator
    22  	return nil
    23  }
    24  
    25  // CreateObject creates an object by its config. The config type must be registered through RegisterConfig().
    26  func CreateObject(ctx context.Context, config interface{}) (interface{}, error) {
    27  	configType := reflect.TypeOf(config)
    28  	creator, found := typeCreatorRegistry[configType]
    29  	if !found {
    30  		return nil, newError(configType.String() + " is not registered").AtError()
    31  	}
    32  	return creator(ctx, config)
    33  }