-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathresponse.go
90 lines (71 loc) · 1.62 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
package azuretls
import (
"encoding/json"
"fmt"
http "github.com/Noooste/fhttp"
"io"
"net/url"
"sync"
)
func (s *Session) buildResponse(response *Response, httpResponse *http.Response) (err error) {
response.RawBody = httpResponse.Body
response.HttpResponse = httpResponse
response.Session = s
var (
wg sync.WaitGroup
headers = make(http.Header, len(httpResponse.Header))
)
if !response.IgnoreBody {
wg.Add(1)
go func() {
defer wg.Done()
if readBody, readErr := response.ReadBody(); readErr == nil {
response.Body = readBody
} else {
err = readErr
}
}()
}
for key, value := range httpResponse.Header {
headers[key] = value
}
response.StatusCode = httpResponse.StatusCode
response.Status = httpResponse.Status
response.Header = headers
var u *url.URL
if response.Url == "" {
response.Url = httpResponse.Request.URL.String()
u = httpResponse.Request.URL
} else {
u, _ = url.Parse(response.Url)
}
cookies := httpResponse.Cookies()
s.CookieJar.SetCookies(u, cookies)
response.Cookies = GetCookiesMap(cookies)
response.ContentLength = httpResponse.ContentLength
wg.Wait()
return
}
func (r *Response) ReadBody() (body []byte, err error) {
defer func() {
_ = r.HttpResponse.Body.Close()
}()
return io.ReadAll(r.HttpResponse.Body)
}
func (r *Response) CloseBody() error {
if r.RawBody != nil {
return r.RawBody.Close()
}
return nil
}
func (r *Response) JSON(v any) error {
if r.Body == nil {
return fmt.Errorf("response body is nil")
}
return json.Unmarshal(r.Body, v)
}
func (r *Response) MustJSON(v any) {
if err := r.JSON(v); err != nil {
panic(err)
}
}