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"
|
2017-02-02 08:42:31 -05:00
|
|
|
"v2ray.com/core/common/errors"
|
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-02-02 08:42:31 -05:00
|
|
|
return nil, errors.New("Core: ", 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
|
|
|
}
|