github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/main/confloader/external/external.go (about)

     1  package external
     2  
     3  //go:generate go run v2ray.com/core/common/errors/errorgen
     4  
     5  import (
     6  	"bytes"
     7  	"io"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"net/url"
    11  	"os"
    12  	"strings"
    13  	"time"
    14  
    15  	"v2ray.com/core/common/buf"
    16  	"v2ray.com/core/common/platform/ctlcmd"
    17  	"v2ray.com/core/main/confloader"
    18  )
    19  
    20  func ConfigLoader(arg string) (out io.Reader, err error) {
    21  
    22  	var data []byte
    23  	if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
    24  		data, err = FetchHTTPContent(arg)
    25  	} else if arg == "stdin:" {
    26  		data, err = ioutil.ReadAll(os.Stdin)
    27  	} else {
    28  		data, err = ioutil.ReadFile(arg)
    29  	}
    30  
    31  	if err != nil {
    32  		return
    33  	}
    34  	out = bytes.NewBuffer(data)
    35  	return
    36  }
    37  
    38  func FetchHTTPContent(target string) ([]byte, error) {
    39  
    40  	parsedTarget, err := url.Parse(target)
    41  	if err != nil {
    42  		return nil, newError("invalid URL: ", target).Base(err)
    43  	}
    44  
    45  	if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" {
    46  		return nil, newError("invalid scheme: ", parsedTarget.Scheme)
    47  	}
    48  
    49  	client := &http.Client{
    50  		Timeout: 30 * time.Second,
    51  	}
    52  	resp, err := client.Do(&http.Request{
    53  		Method: "GET",
    54  		URL:    parsedTarget,
    55  		Close:  true,
    56  	})
    57  	if err != nil {
    58  		return nil, newError("failed to dial to ", target).Base(err)
    59  	}
    60  	defer resp.Body.Close()
    61  
    62  	if resp.StatusCode != 200 {
    63  		return nil, newError("unexpected HTTP status code: ", resp.StatusCode)
    64  	}
    65  
    66  	content, err := buf.ReadAllToBytes(resp.Body)
    67  	if err != nil {
    68  		return nil, newError("failed to read HTTP response").Base(err)
    69  	}
    70  
    71  	return content, nil
    72  }
    73  
    74  func ExtConfigLoader(files []string) (io.Reader, error) {
    75  	buf, err := ctlcmd.Run(append([]string{"config"}, files...), os.Stdin)
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  
    80  	return strings.NewReader(buf.String()), nil
    81  }
    82  
    83  func init() {
    84  	confloader.EffectiveConfigFileLoader = ConfigLoader
    85  	confloader.EffectiveExtConfigLoader = ExtConfigLoader
    86  }