-
Notifications
You must be signed in to change notification settings - Fork 3
/
httpclient.go
70 lines (54 loc) · 1.33 KB
/
httpclient.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
package lib
import (
"github.com/blackmann/go-gurl/fork/http/cookiejar"
"io"
"log"
"net/http"
"strings"
"time"
)
type Client interface {
MakeRequest(request Request) (Response, error)
GetRawCookies() string
}
type DefaultClient struct {
client *http.Client
jar *cookiejar.Jar
}
func NewHttpClient(rawCookies string) DefaultClient {
jar := cookiejar.Jar{}
jar.LoadCookies(strings.NewReader(rawCookies))
return DefaultClient{client: &http.Client{Jar: &jar}, jar: &jar}
}
func (c DefaultClient) MakeRequest(request Request) (Response, error) {
start := time.Now()
req, err := http.NewRequest(request.Address.Method,
request.Address.Url,
strings.NewReader(request.Body))
req.Header = request.Headers
res, err := c.client.Do(req)
if err != nil {
log.Println("Error occurred", err)
return Response{}, err
}
defer res.Body.Close()
responseBody, err := io.ReadAll(res.Body)
if err != nil {
log.Println("Error occurred while reading response body", err)
return Response{}, nil
}
timeTaken := time.Since(start).Milliseconds()
return Response{
Body: responseBody,
Cookies: res.Cookies(),
Headers: res.Header,
Status: res.StatusCode,
Time: timeTaken,
Request: request,
}, nil
}
func (c DefaultClient) GetRawCookies() string {
res := strings.Builder{}
c.jar.AllCookies(&res)
return res.String()
}