1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-10 01:40:44 +00:00
v2fly/main/yaml/yaml.go
Jebbs 9367e9b1f2
V5: YAML support (#475)
* yml support

* code optimize

* remove external conf loaders

* update yaml test
code optimize

* code optimize

* fix a typo

* update convert desc
2020-12-03 06:11:24 +08:00

70 lines
1.4 KiB
Go

package yaml
import (
"bytes"
"errors"
"io"
"io/ioutil"
"v2ray.com/core"
"v2ray.com/core/common"
"v2ray.com/core/common/cmdarg"
"v2ray.com/core/infra/conf/json"
"v2ray.com/core/infra/conf/merge"
"v2ray.com/core/infra/conf/serial"
)
func init() {
common.Must(core.RegisterConfigLoader(&core.ConfigFormat{
Name: []string{"YAML"},
Extension: []string{".yml", ".yaml"},
Loader: func(input interface{}) (*core.Config, error) {
switch v := input.(type) {
case cmdarg.Arg:
bs, err := yamlsToJSONs(v)
if err != nil {
return nil, err
}
data, err := merge.BytesToJSON(bs)
if err != nil {
return nil, err
}
r := bytes.NewReader(data)
cf, err := serial.DecodeJSONConfig(r)
if err != nil {
return nil, err
}
return cf.Build()
case io.Reader:
bs, err := ioutil.ReadAll(v)
if err != nil {
return nil, err
}
bs, err = json.FromYAML(bs)
if err != nil {
return nil, err
}
return serial.LoadJSONConfig(bytes.NewBuffer(bs))
default:
return nil, errors.New("unknow type")
}
},
}))
}
func yamlsToJSONs(files []string) ([][]byte, error) {
jsons := make([][]byte, 0)
for _, file := range files {
bs, err := cmdarg.LoadArgToBytes(file)
if err != nil {
return nil, err
}
j, err := json.FromYAML(bs)
if err != nil {
return nil, err
}
jsons = append(jsons, j)
}
return jsons, nil
}