-
Notifications
You must be signed in to change notification settings - Fork 41
/
debug.go
105 lines (90 loc) · 2.53 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package debug
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"github.com/bububa/oceanengine/marketing-api/util"
)
// 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 := util.GetBufferPool()
defer util.PutBufferPool(buf)
json.Indent(buf, body, "", " ")
log.Printf(format, url, buf.String())
}
// PrintJSONRequest print json request with debug
func PrintJSONRequest(method string, url string, header http.Header, body []byte, debug bool) {
if !debug {
return
}
const format = "[DEBUG] [API] JSON %s %s\n" +
"http request header:\n%s\n" +
"http request body:\n%s\n"
buf := util.GetBufferPool()
defer util.PutBufferPool(buf)
json.Indent(buf, body, "", "\t")
headers := make([]string, 0, len(header))
for k := range header {
headers = append(headers, util.StringsJoin(k, ": ", header.Get(k)))
}
log.Printf(format, method, url, strings.Join(headers, "\n"), buf.String())
}
// PrintPostMultipartRequest print multipart/form-data post request with debug
func PrintPostMultipartRequest(url string, mp map[string]string, debug bool) {
if !debug {
return
}
const format = "[DEBUG] [API] multipart/form-data POST %s\n" +
"http request body:\n%s\n"
bs, _ := json.MarshalIndent(mp, "", "\t")
log.Printf(format, url, bs)
}
// DecodeJSONHttpResponse decode json response with debug
func DecodeJSONHttpResponse(r io.Reader, v interface{}, debug bool) ([]byte, error) {
buf := util.GetBufferPool()
defer util.PutBufferPool(buf)
tee := io.TeeReader(r, buf)
if err := json.NewDecoder(tee).Decode(v); err != nil {
return buf.Bytes(), err
}
if !debug {
return nil, nil
}
bs := buf.Bytes()
debugBuf := util.GetBufferPool()
defer util.PutBufferPool(debugBuf)
debugBuf.Grow(len(bs) + 300)
if err := json.Indent(buf, bs, "", "\t"); err != nil {
return bs, err
}
log.Println(util.StringsJoin("[DEBUG] [API] http response body:\n", string(debugBuf.Bytes())))
return nil, nil
}