-
Notifications
You must be signed in to change notification settings - Fork 42
/
debug.go
84 lines (73 loc) · 1.9 KB
/
debug.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
package debug
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
)
// PrintError print error with debug
func PrintError(err error, debug bool) {
if !debug {
return
}
log.Println("[DEBUG] [ERROR]", err)
}
// PrintStringResponse print string response with debug
func PrintStringResponse(str string, debug bool) {
if !debug {
return
}
log.Println("[DEBUG] [RESPONSE]", str)
}
// PrintGetRequest print get request with debug
func PrintGetRequest(url string, debug bool) {
if !debug {
return
}
log.Println("[DEBUG] [API] GET", url)
}
// PrintPostJSONRequest print json request with debug
func PrintPostJSONRequest(url string, body []byte, debug bool) {
if !debug {
return
}
const format = "[DEBUG] [API] JSON POST %s\n" +
"http request body:\n%s\n"
buf := bytes.NewBuffer(make([]byte, 0, len(body)+1024))
if err := json.Indent(buf, body, "", " "); err == nil {
body = buf.Bytes()
}
log.Printf(format, url, body)
}
// PrintPostMultipartRequest print multipart/form-data post request with debug
func PrintPostMultipartRequest(url string, mp map[string]string, debug bool) {
if !debug {
return
}
body, _ := json.Marshal(mp)
const format = "[DEBUG] [API] multipart/form-data POST %s\n" +
"http request body:\n%s\n"
buf := bytes.NewBuffer(make([]byte, 0, len(body)+1024))
if err := json.Indent(buf, body, "", " "); err == nil {
body = buf.Bytes()
}
log.Printf(format, url, body)
}
// DecodeJSONHttpResponse decode json response with debug
func DecodeJSONHttpResponse(r io.Reader, v interface{}, debug bool) error {
if !debug {
return json.NewDecoder(r).Decode(v)
}
body, err := ioutil.ReadAll(r)
if err != nil {
return err
}
body2 := body
buf := bytes.NewBuffer(make([]byte, 0, len(body2)+1024))
if err := json.Indent(buf, body2, "", " "); err == nil {
body2 = buf.Bytes()
}
log.Printf("[DEBUG] [API] http response body:\n%s\n", body2)
return json.Unmarshal(body, v)
}