1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 01:57:12 -05:00
v2fly/loader.go

43 lines
1.1 KiB
Go
Raw Normal View History

2016-10-14 17:41:41 -04:00
package core
import (
"io"
"io/ioutil"
"github.com/golang/protobuf/proto"
2017-02-22 05:58:55 -05:00
"v2ray.com/core/common"
2016-10-14 17:41:41 -04:00
)
2017-02-10 10:25:54 -05:00
// ConfigLoader is an utility to load V2Ray config from external source.
2016-10-14 17:41:41 -04:00
type ConfigLoader func(input io.Reader) (*Config, error)
2016-10-17 08:35:13 -04:00
var configLoaderCache = make(map[ConfigFormat]ConfigLoader)
2016-10-14 17:41:41 -04:00
2017-02-10 10:25:54 -05:00
// RegisterConfigLoader add a new ConfigLoader.
2016-10-14 17:41:41 -04:00
func RegisterConfigLoader(format ConfigFormat, loader ConfigLoader) error {
configLoaderCache[format] = loader
return nil
}
2017-02-10 10:25:54 -05:00
// LoadConfig loads config with given format from given source.
2016-10-14 17:41:41 -04:00
func LoadConfig(format ConfigFormat, input io.Reader) (*Config, error) {
loader, found := configLoaderCache[format]
if !found {
2017-06-22 18:11:46 -04:00
return nil, newError(ConfigFormat_name[int32(format)], " is not loadable.")
2016-10-14 17:41:41 -04:00
}
return loader(input)
}
2017-02-10 10:25:54 -05:00
func loadProtobufConfig(input io.Reader) (*Config, error) {
2016-10-14 17:41:41 -04: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 17:42:14 -04:00
func init() {
2017-02-22 05:58:55 -05:00
common.Must(RegisterConfigLoader(ConfigFormat_Protobuf, loadProtobufConfig))
2016-10-14 17:42:14 -04:00
}