This repository has been archived by the owner on Sep 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfactorial.go
94 lines (78 loc) · 2.13 KB
/
factorial.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
90
91
92
93
94
package factorial
import (
"bytes"
"log"
"net/http"
"net/url"
)
const factorialAPI = "https://api.factorialhr.com"
// New builds a Factorial client from the provided accessToken and options.
func New(opts ...Option) (*Client, error) {
c := &Client{
apiURL: factorialAPI,
}
for _, opt := range opts {
opt(c)
}
return c, nil
}
// WithOAuth2Client provides a custom http client to the client.
func WithOAuth2Client(cli *http.Client) func(*Client) {
return func(c *Client) {
c.Client = cli
}
}
// WithAPIURL sets the API URL for the client.
// Useful for testing.
func WithAPIURL(url string) func(*Client) {
return func(c *Client) {
c.apiURL = url
}
}
// Option defines an option for a Client.
type Option func(*Client)
// Client for the Factorial API.
type Client struct {
*http.Client
apiURL string
}
func (c Client) delete(endpoint string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodDelete, c.apiURL+endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
return c.Do(req)
}
func (c Client) get(endpoint string, q url.Values) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, c.apiURL+endpoint, nil)
if err != nil {
return nil, err
}
if q != nil {
req.URL.RawQuery = q.Encode()
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
return c.Do(req)
}
func (c Client) post(endpoint string, body []byte) (*http.Response, error) {
log.Println("[DEBUG] url", c.apiURL+endpoint, string(body))
req, err := http.NewRequest(http.MethodPost, c.apiURL+endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
return c.Do(req)
}
func (c Client) put(endpoint string, body []byte) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPut, c.apiURL+endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
return c.Do(req)
}