-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bamboohr.go
84 lines (67 loc) · 1.72 KB
/
bamboohr.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
package bamboohr
import (
"fmt"
"io/ioutil"
"net/http"
)
// Client holds the client information for our BambooHR API calls
type Client struct {
APIEndpoint string
APIKey string
HTTPClient *http.Client
}
// BBHRNewInput is used as input to the New() function
type BBHRNewInput struct {
Version string
Company string
APIKey string
}
// New creates a new BambooHR API Client and returns it to the caller
func New(args BBHRNewInput) (*Client, error) {
newClient := &Client{}
// Default version to v1
if args.Version == "" {
args.Version = "v1"
}
if args.Company == "" {
return newClient, fmt.Errorf("missing arg: Company")
}
if args.APIKey == "" {
return newClient, fmt.Errorf("missing arg: APIKey")
} else {
newClient.APIKey = args.APIKey
}
newClient.APIEndpoint = fmt.Sprintf("https://api.bamboohr.com/api/gateway.php/%s/%s", args.Company, args.Version)
newClient.HTTPClient = http.DefaultClient
return newClient, nil
}
// sendRequest sends the actual http request to BBHR
func (b *Client) sendRequest(req *http.Request) ([]byte, error) {
req.Header.Add("ACCEPT", "application/json")
req.SetBasicAuth(b.APIKey, "x")
resp, err := b.HTTPClient.Do(req)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return []byte{}, fmt.Errorf("status code not 200: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
return body, err
}
// getRequest abstraction
func (b *Client) getRequest(endpointURL string) ([]byte, error) {
req, err := http.NewRequest("GET", endpointURL, nil)
if err != nil {
return []byte{}, err
}
resp, err := b.sendRequest(req)
if err != nil {
return []byte{}, err
}
return resp, nil
}