-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcmd_http_get.go
109 lines (83 loc) · 2.16 KB
/
cmd_http_get.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"flag"
"fmt"
"io"
"net/http"
"sort"
"strings"
)
// Structure for our options and state.
type httpGetCommand struct {
// Show headers?
headers bool
// Show body?
body bool
}
// Arguments adds per-command args to the object.
func (hg *httpGetCommand) Arguments(f *flag.FlagSet) {
f.BoolVar(&hg.body, "body", true, "Show the response body.")
f.BoolVar(&hg.headers, "headers", false, "Show the response headers.")
}
// Info returns the name of this subcommand.
func (hg *httpGetCommand) Info() (string, string) {
return "http-get", `Download and display the contents of a remote URL.
Details:
This command is very much curl-lite, allowing you to fetch the contents of
a remote URL, with no configuration options of any kind.
While it is unusual to find hosts without curl or wget installed it does
happen, this command will bridge the gap a little.
Examples:
$ sysbox http-get https://steve.fi/`
}
// Execute is invoked if the user specifies `http-get` as the subcommand.
func (hg *httpGetCommand) Execute(args []string) int {
// Ensure we have only a single URL
if len(args) != 1 {
fmt.Printf("Usage: http-get URL\n")
return 1
}
// The URL
url := args[0]
// We'll default to https if the protocol isn't specified.
if !strings.HasPrefix(url, "http") {
url = "https://" + url
}
// Make the request
response, err := http.Get(url)
if err != nil {
fmt.Printf("error fetching %s: %s", url, err.Error())
return 1
}
// Get the body.
defer response.Body.Close()
contents, err := io.ReadAll(response.Body)
if err != nil {
fmt.Printf("error: %s", err.Error())
return 1
}
// Show header?
if hg.headers {
// Keep a list of the headers here for sort/display
headers := []string{}
// Copy the headers
for header := range response.Header {
headers = append(headers, header)
}
// Sort them
sort.Strings(headers)
// Output them
for _, header := range headers {
fmt.Printf("%s: %s\n", header, response.Header.Get(header))
}
}
// If showing header and body separate them both
if hg.headers && hg.body {
fmt.Printf("\n")
}
// Show body?
if hg.body {
fmt.Printf("%s\n", string(contents))
}
return 0
}