-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
91 lines (79 loc) · 1.87 KB
/
main.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
package main
import (
"bufio"
"fmt"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"github.com/henvic/httpretty"
)
func main() {
logger := &httpretty.Logger{
Time: true,
TLS: true,
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
Colors: true, // erase line if you don't like colors
Formatters: []httpretty.Formatter{&httpretty.JSONFormatter{}},
}
// Using a custom HTTP client using the logger RoundTripper, rather than http.DefaultClient.
client := &http.Client{
Transport: logger.RoundTripper(http.DefaultTransport),
}
fmt.Print("httprepl is a small HTTP client REPL (read-eval-print-loop) program example\n\n")
help()
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("$ ")
readEvalPrint(reader, client)
}
}
func readEvalPrint(reader *bufio.Reader, client *http.Client) {
s, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintf(os.Stderr, "cannot read stdin: %v\n", err)
os.Exit(1)
}
if runtime.GOOS == "windows" {
s = strings.TrimRight(s, "\r\n")
} else {
s = strings.TrimRight(s, "\n")
}
s = strings.TrimSpace(s)
switch {
case s == "exit":
os.Exit(0)
case s == "help":
help()
return
case s == "":
return
case s == "get":
fmt.Fprintln(os.Stderr, "missing address")
case !strings.HasPrefix(s, "get "):
fmt.Fprint(os.Stderr, "invalid command\n\n")
return
}
s = strings.TrimPrefix(s, "get ")
uri, err := url.Parse(s)
if err == nil && uri.Scheme == "" {
uri.Scheme = "http"
s = uri.String()
}
// we just ignore the request contents but you can see it printed thanks to the logger.
if _, err := client.Get(s); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n\n", err)
}
fmt.Println()
}
func help() {
fmt.Print(`Commands available:
get <address> URL to get. Example: "get www.google.com"
help This command list
exit Quit the application
`)
}