loader.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package core
  2. import (
  3. "io"
  4. "io/ioutil"
  5. "github.com/golang/protobuf/proto"
  6. "v2ray.com/core/common/errors"
  7. )
  8. // ConfigLoader is an utility to load V2Ray config from external source.
  9. type ConfigLoader func(input io.Reader) (*Config, error)
  10. var configLoaderCache = make(map[ConfigFormat]ConfigLoader)
  11. // RegisterConfigLoader add a new ConfigLoader.
  12. func RegisterConfigLoader(format ConfigFormat, loader ConfigLoader) error {
  13. configLoaderCache[format] = loader
  14. return nil
  15. }
  16. // LoadConfig loads config with given format from given source.
  17. func LoadConfig(format ConfigFormat, input io.Reader) (*Config, error) {
  18. loader, found := configLoaderCache[format]
  19. if !found {
  20. return nil, errors.New("Core: ", ConfigFormat_name[int32(format)], " is not loadable.")
  21. }
  22. return loader(input)
  23. }
  24. func loadProtobufConfig(input io.Reader) (*Config, error) {
  25. config := new(Config)
  26. data, _ := ioutil.ReadAll(input)
  27. if err := proto.Unmarshal(data, config); err != nil {
  28. return nil, err
  29. }
  30. return config, nil
  31. }
  32. func init() {
  33. RegisterConfigLoader(ConfigFormat_Protobuf, loadProtobufConfig)
  34. }