loader.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package core
  2. import (
  3. "io"
  4. "v2ray.com/core/common"
  5. "v2ray.com/core/common/buf"
  6. "github.com/golang/protobuf/proto"
  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, newError(ConfigFormat_name[int32(format)], " is not loadable.").AtWarning()
  21. }
  22. return loader(input)
  23. }
  24. func loadProtobufConfig(input io.Reader) (*Config, error) {
  25. config := new(Config)
  26. data, err := buf.ReadAllToBytes(input)
  27. if err != nil {
  28. return nil, err
  29. }
  30. if err := proto.Unmarshal(data, config); err != nil {
  31. return nil, err
  32. }
  33. return config, nil
  34. }
  35. func init() {
  36. common.Must(RegisterConfigLoader(ConfigFormat_Protobuf, loadProtobufConfig))
  37. }