-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
76 lines (61 loc) · 1.46 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
package headhunter
import (
"errors"
"fmt"
"io"
"net/http"
)
const (
baseURL = "https://api.hh.ru"
methodGET = "GET"
methodPOST = "POST"
methodDELETE = "DELETE"
)
type Client struct {
httpClient *http.Client
clientID string
clientSecret string
redirectURI string
UrlParams *Params
}
func NewClient(clientID string, clientSecret string, redirectURI string) (*Client, error) {
if clientID == "" {
return nil, errors.New("client id is empty")
}
if clientSecret == "" {
return nil, errors.New("client secret is empty")
}
if redirectURI == "" {
return nil, errors.New("redirect uri is empty")
}
return &Client{
httpClient: &http.Client{},
clientID: clientID,
clientSecret: clientSecret,
redirectURI: redirectURI,
UrlParams: NewParams(),
}, nil
}
func (c *Client) sendRequest(method string, endpoint string, params string, token string) (string, error) {
req, err := http.NewRequest(method, endpoint+params, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+token)
res, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK &&
res.StatusCode != http.StatusCreated &&
res.StatusCode != http.StatusNoContent {
err := fmt.Sprintf("API Error! Status code %d", res.StatusCode)
return "", errors.New(err)
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(resBody), nil
}