loader.go 1.1 KB

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