/
hip.go
99 lines (84 loc) · 1.77 KB
/
hip.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/bobappleyard/readline"
"github.com/codegangsta/cli"
"github.com/wsxiaoys/terminal/color"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
)
func main() {
address := ""
commands := []cli.Command{
{
Name: "get",
ShortName: "g",
Usage: "Make a get request",
Action: func(c *cli.Context) {
url := address + c.Args()[0]
res, err := http.Get(url)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
printResponse(res)
buf := new(bytes.Buffer)
body, _ := ioutil.ReadAll(res.Body)
json.Indent(buf, body, "", " ")
s := buf.String()
s = strings.Replace(s, "@", "@@", -1)
reg, _ := regexp.Compile("(\".*?:)(.*).?([,\r,\n])")
s = reg.ReplaceAllString(s, "@b$1@c$2@|$3")
color.Println(s)
},
},
}
app := cli.NewApp()
app.Commands = commands
app.Version = "0.0.1"
app.Action = func(ctx *cli.Context) {
if len(ctx.Args()) == 0 {
cli.ShowAppHelp(ctx)
os.Exit(1)
}
address = ctx.Args()[0]
console := cli.NewApp()
console.Commands = commands
console.Action = func(c *cli.Context) {
fmt.Println("Command not found. Type 'help' for a list of commands.")
}
for {
line, err := readline.String("> ")
if err == io.EOF {
break
}
if err != nil {
fmt.Println("error: ", err)
break
}
readline.AddHistory(line)
console.Run(strings.Fields("cmd " + line))
}
}
app.Run(os.Args)
}
func printResponse(res *http.Response) {
color.Println(res.Proto, statusColor(res.StatusCode)+res.Status)
for k := range res.Header {
color.Println(k+":", "@{!c}"+res.Header.Get(k))
}
fmt.Println("")
}
func statusColor(code int) string {
if code >= 400 {
return "@{r!}"
} else {
return "@{g!}"
}
}