File: fetch.go

package info (click to toggle)
golang-v2ray-core 4.34.0%2Bds-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,100 kB
  • sloc: sh: 404; makefile: 50; asm: 38
file content (78 lines) | stat: -rw-r--r-- 1,599 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package control

import (
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"v2ray.com/core/common"
	"v2ray.com/core/common/buf"
)

type FetchCommand struct{}

func (c *FetchCommand) Name() string {
	return "fetch"
}

func (c *FetchCommand) Description() Description {
	return Description{
		Short: "Fetch resources",
		Usage: []string{"v2ctl fetch <url>"},
	}
}

func (c *FetchCommand) Execute(args []string) error {
	if len(args) < 1 {
		return newError("empty url")
	}
	content, err := FetchHTTPContent(args[0])
	if err != nil {
		return newError("failed to read HTTP response").Base(err)
	}

	os.Stdout.Write(content)
	return nil
}

// 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 init() {
	common.Must(RegisterCommand(&FetchCommand{}))
}