/
model.go
88 lines (77 loc) · 2.18 KB
/
model.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
package lark
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
type RawRequest struct {
Header http.Header
RawBody []byte
}
func NewRawRequest(req *http.Request) (*RawRequest, error) {
rawBody, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
return &RawRequest{
Header: req.Header,
RawBody: rawBody,
}, nil
}
func (req RawRequest) RequestId() string {
logID := req.Header.Get(httpHeaderKeyLogId)
if logID != "" {
return logID
}
return req.Header.Get(httpHeaderKeyRequestId)
}
func (req RawRequest) JSONUnmarshalBody(val interface{}) error {
if !strings.Contains(req.Header.Get(contentTypeHeader), contentTypeJson) {
return fmt.Errorf("req content-type not json, req: %v", req)
}
return json.Unmarshal(req.RawBody, val)
}
func (req RawRequest) String() string {
return fmt.Sprintf("Header:%v, Content-Type: %s, Body: %v",
req.Header, req.Header.Get(contentTypeHeader), string(req.RawBody))
}
type RawResponse struct {
StatusCode int `json:"-"`
Header http.Header `json:"-"`
RawBody []byte `json:"-"`
}
func (resp RawResponse) Write(writer http.ResponseWriter) {
writer.WriteHeader(resp.StatusCode)
for k, vs := range resp.Header {
for _, v := range vs {
writer.Header().Add(k, v)
}
}
if _, err := writer.Write(resp.RawBody); err != nil {
panic(err)
}
}
func (resp RawResponse) JSONUnmarshalBody(val interface{}) error {
if !strings.Contains(resp.Header.Get(contentTypeHeader), contentTypeJson) {
return fmt.Errorf("response content-type not json, response: %v", resp)
}
return json.Unmarshal(resp.RawBody, val)
}
func (resp RawResponse) RequestId() string {
logID := resp.Header.Get(httpHeaderKeyLogId)
if logID != "" {
return logID
}
return resp.Header.Get(httpHeaderKeyRequestId)
}
func (resp RawResponse) String() string {
contentType := resp.Header.Get(contentTypeHeader)
body := fmt.Sprintf("<binary> len %d", len(resp.RawBody))
if strings.Contains(contentType, "json") || strings.Contains(contentType, "text") {
body = string(resp.RawBody)
}
return fmt.Sprintf("StatusCode: %d, Header:%v, Content-Type: %s, Body: %v", resp.StatusCode,
resp.Header, resp.Header.Get(contentTypeHeader), body)
}