1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-05 17:57:42 -05:00
v2fly/main/confloader/external/external.go

87 lines
1.8 KiB
Go
Raw Normal View History

2019-12-15 20:33:41 -05:00
package external
2020-01-02 20:26:48 -05:00
//go:generate errorgen
2019-12-15 20:33:41 -05:00
import (
2020-01-02 20:26:48 -05:00
"bytes"
2019-12-15 20:33:41 -05:00
"io"
2020-01-02 20:26:48 -05:00
"io/ioutil"
"net/http"
"net/url"
2019-12-15 20:33:41 -05:00
"os"
"strings"
2020-01-02 20:26:48 -05:00
"time"
2019-12-15 20:33:41 -05:00
"v2ray.com/core/common/buf"
"v2ray.com/core/common/platform/ctlcmd"
"v2ray.com/core/main/confloader"
)
2020-01-02 20:26:48 -05:00
func ConfigLoader(arg string) (out io.Reader, err error) {
var data []byte
if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
data, err = FetchHTTPContent(arg)
} else if arg == "stdin:" {
data, err = ioutil.ReadAll(os.Stdin)
} else {
data, err = ioutil.ReadFile(arg)
}
if err != nil {
return
}
out = bytes.NewBuffer(data)
return
}
func FetchHTTPContent(target string) ([]byte, error) {
2019-12-15 20:33:41 -05:00
2020-01-02 20:26:48 -05:00
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,
2019-12-15 20:33:41 -05:00
}
2020-01-02 20:26:48 -05:00
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()
2019-12-15 20:33:41 -05:00
2020-01-02 20:26:48 -05:00
if resp.StatusCode != 200 {
return nil, newError("unexpected HTTP status code: ", resp.StatusCode)
2019-12-15 20:33:41 -05:00
}
2020-01-02 20:26:48 -05:00
content, err := buf.ReadAllToBytes(resp.Body)
2019-12-15 20:33:41 -05:00
if err != nil {
2020-01-02 20:26:48 -05:00
return nil, newError("failed to read HTTP response").Base(err)
2019-12-15 20:33:41 -05:00
}
2020-01-02 20:26:48 -05:00
return content, nil
}
func ExtConfigLoader(files []string) (io.Reader, error) {
buf, err := ctlcmd.Run(append([]string{"config"}, files...), os.Stdin)
2019-12-15 20:33:41 -05:00
if err != nil {
2020-01-02 20:26:48 -05:00
return nil, err
2019-12-15 20:33:41 -05:00
}
2020-01-02 20:26:48 -05:00
return strings.NewReader(buf.String()), nil
2019-12-15 20:33:41 -05:00
}
func init() {
2020-01-02 20:26:48 -05:00
confloader.EffectiveConfigFileLoader = ConfigLoader
confloader.EffectiveExtConfigLoader = ExtConfigLoader
2019-12-15 20:33:41 -05:00
}