/
request.go
72 lines (64 loc) · 1.53 KB
/
request.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
package feedbin
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
func (r *Feedbin) request(ctx context.Context, method, uri string, body io.Reader, withAuth bool, resp interface{}) (string, error) {
req, err := http.NewRequest(method, uri, body)
if err != nil {
return "", err
}
if withAuth && r.password != "" {
req.SetBasicAuth(r.username, r.password)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("User-Agent", fmt.Sprintf("go-feedbin/%s (https://github.com/chyroc/go-feedbin)", version))
response, err := r.httpClient.Do(req)
if err != nil {
return "", err
}
bs, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
if response.StatusCode == http.StatusUnauthorized {
if s := string(bs); s != "" {
return "", fmt.Errorf(strings.TrimSpace(s))
}
return "", fmt.Errorf(strings.TrimSpace(response.Status))
}
res := new(baseResp)
if _ = json.Unmarshal(bs, res); res.Err() != nil {
return "", res.Err()
}
if resp != nil {
if err = json.Unmarshal(bs, resp); err != nil {
return "", err
}
}
return string(bs), nil
}
type baseResp struct {
Status int `json:"status"`
Message interface{} `json:"message"`
Messages string `json:"messages"`
Errors []struct {
Pages string `json:"pages"`
} `json:"errors"`
}
func (r *baseResp) Err() error {
if r.Messages != "" {
return fmt.Errorf(r.Messages)
}
for _, v := range r.Errors {
if v.Pages != "" {
return fmt.Errorf(v.Pages)
}
}
return nil
}