1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/infra/conf/merge/file.go
Jebbs ff59bd37ce
v5: New multi-json loader (#451)
* scalable commands column

* new multi-json loader
For both internal & external json loader

This commit also:
* applies -confdir to other formats, e.g. "yaml" in the future
* multiple assign of -confdir is accepted
* add flag to load confdir recursively
* config loader can have alias name
* json loader also accepts .jsonc
* add merge command
* add help topics for json merge, format loader
* format loaders don't panic

* apply lint style

* add merge test

* merge same tag in array, solve v2fly/discussion#97

* apply lint style

* merge code optimize

* fix merge cmdarg.Arg

* update cmd description

* improve merge logic
* fix zero value overwrite
* fix "null" lost after array merge

* code optimize

* fix merged slices not sorted

* code optimize

* add package doc

* fix a typo
2020-11-28 22:06:03 +08:00

79 lines
1.7 KiB
Go

package merge
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"time"
"v2ray.com/core/common/buf"
"v2ray.com/core/infra/conf/serial"
)
// loadArg loads one arg, maybe an remote url, or local file path
func loadArg(arg string) (out io.Reader, err error) {
var data []byte
switch {
case strings.HasPrefix(arg, "http://"), strings.HasPrefix(arg, "https://"):
data, err = fetchHTTPContent(arg)
case (arg == "stdin:"):
data, err = ioutil.ReadAll(os.Stdin)
default:
data, err = ioutil.ReadFile(arg)
}
if err != nil {
return
}
out = bytes.NewBuffer(data)
return
}
// fetchHTTPContent dials https for remote content
func fetchHTTPContent(target string) ([]byte, error) {
parsedTarget, err := url.Parse(target)
if err != nil {
return nil, newError("invalid URL: ", target).Base(err)
}
if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" {
return nil, newError("invalid scheme: ", parsedTarget.Scheme)
}
client := &http.Client{
Timeout: 30 * time.Second,
}
resp, err := client.Do(&http.Request{
Method: "GET",
URL: parsedTarget,
Close: true,
})
if err != nil {
return nil, newError("failed to dial to ", target).Base(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, newError("unexpected HTTP status code: ", resp.StatusCode)
}
content, err := buf.ReadAllToBytes(resp.Body)
if err != nil {
return nil, newError("failed to read HTTP response").Base(err)
}
return content, nil
}
func decode(r io.Reader) (map[string]interface{}, error) {
c := make(map[string]interface{})
err := serial.DecodeJSON(r, &c)
if err != nil {
return nil, err
}
return c, nil
}