v2ray-core/loader.go

43 lines
1.1 KiB
Go
Raw Normal View History

2016-10-14 21:41:41 +00:00
package core
import (
"io"
"io/ioutil"
"github.com/golang/protobuf/proto"
2017-02-22 10:58:55 +00:00
"v2ray.com/core/common"
2016-10-14 21:41:41 +00:00
)
2017-02-10 15:25:54 +00:00
// ConfigLoader is an utility to load V2Ray config from external source.
2016-10-14 21:41:41 +00:00
type ConfigLoader func(input io.Reader) (*Config, error)
2016-10-17 12:35:13 +00:00
var configLoaderCache = make(map[ConfigFormat]ConfigLoader)
2016-10-14 21:41:41 +00:00
2017-02-10 15:25:54 +00:00
// RegisterConfigLoader add a new ConfigLoader.
2016-10-14 21:41:41 +00:00
func RegisterConfigLoader(format ConfigFormat, loader ConfigLoader) error {
configLoaderCache[format] = loader
return nil
}
2017-02-10 15:25:54 +00:00
// LoadConfig loads config with given format from given source.
2016-10-14 21:41:41 +00:00
func LoadConfig(format ConfigFormat, input io.Reader) (*Config, error) {
loader, found := configLoaderCache[format]
if !found {
2017-04-08 23:43:25 +00:00
return nil, newError("Core: ", ConfigFormat_name[int32(format)], " is not loadable.")
2016-10-14 21:41:41 +00:00
}
return loader(input)
}
2017-02-10 15:25:54 +00:00
func loadProtobufConfig(input io.Reader) (*Config, error) {
2016-10-14 21:41:41 +00:00
config := new(Config)
data, _ := ioutil.ReadAll(input)
if err := proto.Unmarshal(data, config); err != nil {
return nil, err
}
return config, nil
}
2016-10-14 21:42:14 +00:00
func init() {
2017-02-22 10:58:55 +00:00
common.Must(RegisterConfigLoader(ConfigFormat_Protobuf, loadProtobufConfig))
2016-10-14 21:42:14 +00:00
}