1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/loader.go

47 lines
1.1 KiB
Go
Raw Normal View History

2016-10-14 17:41:41 -04:00
package core
import (
"io"
2017-02-22 05:58:55 -05:00
"v2ray.com/core/common"
2017-11-03 20:33:28 -04:00
"v2ray.com/core/common/buf"
"github.com/golang/protobuf/proto"
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)
2017-11-03 20:33:28 -04:00
data, err := buf.ReadAllToBytes(input)
if err != nil {
return nil, err
}
2016-10-14 17:41:41 -04:00
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
}