1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2026-01-06 01:05:35 -05:00

abstract type for conf load func

This commit is contained in:
vcptr
2019-12-14 23:29:54 +08:00
parent 61e95e06c0
commit 1bb34bfe17
5 changed files with 95 additions and 57 deletions

View File

@@ -4,11 +4,13 @@ package core
import (
"io"
"io/ioutil"
"strings"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/cmdarg"
)
// ConfigFormat is a configurable format of V2Ray config file.
@@ -19,7 +21,7 @@ type ConfigFormat struct {
}
// ConfigLoader is a utility to load V2Ray config from external source.
type ConfigLoader func(input io.Reader) (*Config, error)
type ConfigLoader func(input interface{}) (*Config, error)
var (
configLoaderByName = make(map[string]*ConfigFormat)
@@ -54,7 +56,10 @@ func getExtension(filename string) string {
}
// LoadConfig loads config with given format from given source.
func LoadConfig(formatName string, filename string, input io.Reader) (*Config, error) {
// input accepts 2 different types:
// * []string slice of multiple filename/url(s) to open to read
// * io.Reader that reads a config content (the original way)
func LoadConfig(formatName string, filename string, input interface{}) (*Config, error) {
ext := getExtension(filename)
if len(ext) > 0 {
if f, found := configLoaderByExt[ext]; found {
@@ -69,12 +74,8 @@ func LoadConfig(formatName string, filename string, input io.Reader) (*Config, e
return nil, newError("Unable to load config in ", formatName).AtWarning()
}
func loadProtobufConfig(input io.Reader) (*Config, error) {
func loadProtobufConfig(data []byte) (*Config, error) {
config := new(Config)
data, err := buf.ReadAllToBytes(input)
if err != nil {
return nil, err
}
if err := proto.Unmarshal(data, config); err != nil {
return nil, err
}
@@ -85,6 +86,23 @@ func init() {
common.Must(RegisterConfigLoader(&ConfigFormat{
Name: "Protobuf",
Extension: []string{"pb"},
Loader: loadProtobufConfig,
Loader: func(input interface{}) (*Config, error) {
switch v := input.(type) {
case cmdarg.Arg:
if len(v) == 0 {
return nil, newError("input has no element")
}
// pb type can only handle the first config
data, err := ioutil.ReadFile(v[0])
common.Must(err)
return loadProtobufConfig(data)
case io.Reader:
data, err := buf.ReadAllToBytes(v)
common.Must(err)
return loadProtobufConfig(data)
default:
return nil, newError("unknow type")
}
},
}))
}