-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
65 lines (51 loc) · 1.48 KB
/
client.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
package feedly
import (
"errors"
"io"
"net/http"
"time"
)
type ClientError struct {
error
}
type RequestError struct {
error
}
type Client struct {
// Client is a wrapper around the http.Client struct.
// It is used to make requests to the RSS feed.
c *http.Client
}
// NewClient returns a new instance of Client.
// Set timeout to 10 seconds
func NewClient() *Client {
c := &http.Client{}
c.Timeout = 10 * time.Second
return &Client{c}
}
// FetchFeed fetches the RSS feed from the given url.
// It returns the response code, the response body and any errors.
func (c Client) FetchFeed(url string) (respCode uint32, res []byte, err RequestError) {
// MakeRequest makes a GET request to the RSS feed.
// It returns the response and any errors.
req, newReqErr := http.NewRequest("GET", url, nil)
if newReqErr != nil {
return 0, nil, RequestError{err}
}
// se content type to xml
req.Header.Set("Content-Type", "application/xml")
// set user agent
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36")
resp, doErr := c.c.Do(req)
if doErr != nil {
return 0, nil, RequestError{doErr}
}
res, rerr := io.ReadAll(resp.Body)
if rerr != nil {
return uint32(resp.StatusCode), nil, RequestError{rerr}
}
if resp.StatusCode != http.StatusOK {
return uint32(resp.StatusCode), nil, RequestError{errors.New(resp.Status)}
}
return uint32(resp.StatusCode), res, RequestError{nil}
}