forked from tmtk75/kii-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
99 lines (84 loc) · 2.33 KB
/
http.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 kiicli
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
)
type HttpResponse http.Response
func (self *HttpResponse) Bytes() []byte {
b, _ := ioutil.ReadAll(self.Body)
return b
}
func HttpPostJson(path string, headers map[string]string, body interface{}) *HttpResponse {
reqbody, _ := json.Marshal(body)
return HttpPost(path, headers, bytes.NewReader(reqbody))
}
func HttpPost(path string, headers Headers, r io.Reader) *HttpResponse {
return httpRequest("POST", path, headers, r)
}
func HttpGet(path string, headers Headers) *HttpResponse {
empty := []byte{}
return httpRequest("GET", path, headers, bytes.NewReader(empty))
}
func HttpPut(path string, headers Headers, r io.Reader) *HttpResponse {
return httpRequest("PUT", path, headers, r)
}
func HttpDelete(path string, headers Headers) *HttpResponse {
empty := []byte{}
return httpRequest("DELETE", path, headers, bytes.NewReader(empty))
}
func httpRequest(method string, path string, headers Headers, r io.Reader) *HttpResponse {
p := Profile()
ep := fmt.Sprintf("%s%s", p.EndpointUrl(), path)
logger.Printf("%s %s", method, ep)
body, _ := ioutil.ReadAll(r)
req, err := http.NewRequest(method, ep, bytes.NewReader(body))
if err != nil {
log.Fatalf("%v", err)
}
for k, v := range headers {
req.Header.Add(k, v)
logger.Printf("%s: %s", k, v)
}
if p.Curl {
printCurlString(method, headers, ep, body)
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Fatalf("%v", err)
}
logger.Printf("status-code: %v", res.StatusCode)
if res.StatusCode/100 != 2 && !p.SuppressExit {
b, _ := ioutil.ReadAll(res.Body)
log.Fatalf("%s", string(b))
}
hr := HttpResponse(*res)
return &hr
}
func printCurlString(method string, header Headers, endpoint string, body []byte) {
hs := make([]string, 0)
for k, v := range header {
hs = append(hs, fmt.Sprintf("-H'%s: %s'", k, v))
}
h := strings.Join(hs, " ")
// ~/.kii/${app_id}/curl.{something}
p := Profile()
dataDir := fmt.Sprintf("%v", metaFilePath(p.AppId, ""))
tmp, err := ioutil.TempFile(dataDir, "curl-data.")
if err != nil {
log.Fatalf("%v", err)
}
tmp.Write(body)
defer tmp.Close()
if len(body) > 0 {
logger.Printf("curl -X%s %s %s -d @%v\n\n", method, h, endpoint, tmp.Name())
} else {
logger.Printf("curl -X%s %s %s\n\n", method, h, endpoint)
}
}