config_loader.go 906 B

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