-
Notifications
You must be signed in to change notification settings - Fork 2
/
response.go
183 lines (157 loc) · 3.97 KB
/
response.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package pangea
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path"
pu "github.com/pangeacyber/pangea-go/pangea-sdk/v3/internal/pangeautil"
)
type ResponseHeader struct {
// The request ID
RequestID *string `json:"request_id"`
// The time the request was issued, ISO8601
RequestTime *string `json:"request_time"`
// The time the response was issued, ISO8601
ResponseTime *string `json:"response_time"`
// The HTTP status code msg
Status *string `json:"status"`
// The summary of the response
Summary *string `json:"summary"`
}
type Response struct {
ResponseHeader
HTTPResponse *http.Response
AttachedFiles []AttachedFile
// Query raw result
RawResult json.RawMessage `json:"result"`
rawResponse []byte
}
func (r *ResponseHeader) String() string {
if r == nil {
return ""
}
return fmt.Sprintf("request_id: %v, request_time: %v, response_time: %v, status: %v, summary: %v",
StringValue(r.RequestID), StringValue(r.RequestTime), StringValue(r.ResponseTime),
StringValue(r.Status), StringValue(r.Summary))
}
type PangeaResponse[T any] struct {
Response
Result *T
AcceptedResult *AcceptedResult
}
func (r *Response) UnmarshalResult(target interface{}) error {
return json.Unmarshal(r.RawResult, target)
}
// newResponse takes a http.Response and tries to parse the body into a base pangea API response.
func newResponse(r *http.Response) (*Response, error) {
response := &Response{HTTPResponse: r}
defer r.Body.Close()
var data []byte
if isMultipart(r.Header) {
boundary, err := pu.GetBoundary(r.Header.Get("Content-Type"))
if err != nil {
return nil, err
}
// Create a multipart reader
multipartReader := multipart.NewReader(r.Body, boundary)
var n = 0
// Iterate through each part in the multipart response
for {
part, err := multipartReader.NextRawPart()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
defer part.Close()
if n == 0 {
// Read the part's content
data, err = io.ReadAll(part)
if err != nil {
return nil, err
}
} else {
// Read the part's content
fb, err := io.ReadAll(part)
if err != nil {
return nil, err
}
af := AttachedFile{
Filename: part.FileName(),
File: fb,
ContentType: part.Header.Get("Content-Type"),
}
response.AttachedFiles = append(response.AttachedFiles, af)
}
n += 1
}
} else {
var err error
data, err = io.ReadAll(r.Body)
if err != nil {
return nil, NewUnmarshalError(err, []byte{}, r)
}
}
response.rawResponse = data
if err := json.Unmarshal(data, response); err != nil {
return nil, NewUnmarshalError(err, data, r)
}
return response, nil
}
// Check if the response is multipart
func isMultipart(header http.Header) bool {
contentType := header.Get("Content-Type")
return len(contentType) > 0 && contentType[:10] == "multipart/"
}
type AttachedFile struct {
Filename string
File []byte
ContentType string
}
type AttachedFileSaveInfo struct {
Filename string
Folder string
}
func (af AttachedFile) Save(info AttachedFileSaveInfo) error {
folder := "./"
if info.Folder != "" {
folder = info.Folder
}
filename := "defaultFilename"
if af.Filename != "" {
filename = af.Filename
}
if info.Filename != "" {
filename = info.Filename
}
if _, err := os.Stat(folder); os.IsNotExist(err) {
// Directory does not exist, create it
err := os.MkdirAll(folder, os.ModePerm)
if err != nil {
return err
}
}
filePath := path.Join(folder, filename)
err := os.WriteFile(filePath, af.File, 0644)
if err != nil {
return err
}
return nil
}
// MarshalJSON implements the json.Marshaler interface for CustomType.
func (r Response) MarshalJSON() ([]byte, error) {
if r.rawResponse == nil {
return nil, errors.New("unable to read response body")
}
b := make([]byte, len(r.rawResponse))
nc := copy(b, r.rawResponse)
if nc != len(r.rawResponse) {
return nil, errors.New("unable to copy raw response")
}
return b, nil
}