-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
89 lines (71 loc) · 1.78 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package octopus
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"github.com/pkg/errors"
)
const ApiBaseUrl = "https://strong-octopus.com"
type Client struct {
presharedKey string
httpClient http.Client
}
func NewClient(presharedKey string) Client {
return Client{
presharedKey: presharedKey,
httpClient: http.Client{},
}
}
type ApiError struct {
Message string
}
func (e *ApiError) Error() string {
return e.Message
}
func (c *Client) SearchByKeyword(keyword string, page int) ([]Article, error) {
const path = "/articles/search"
params := url.Values{}
params.Add("keyword", keyword)
params.Add("page", strconv.Itoa(page))
responseBody, err := c.request("GET", path, params)
if err != nil {
return nil, err
}
var searchResponse struct {
Articles []Article `json:"articles"`
}
if err := json.Unmarshal(responseBody, &searchResponse); err != nil {
return nil, errors.Wrap(err, "failed to decode json")
}
return searchResponse.Articles, nil
}
func (c *Client) request(method string, path string, params url.Values) ([]byte, error) {
var endpoint = fmt.Sprintf("%s%s?%s", ApiBaseUrl, path, params.Encode())
req, err := http.NewRequest(method, endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.presharedKey))
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
var errorResponse struct {
Message string `json:"error"`
}
if err := json.Unmarshal(body, &errorResponse); err != nil {
return nil, errors.Wrap(err, "failed to decode json")
}
return nil, &ApiError{Message: errorResponse.Message}
}
return body, nil
}