-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhabitica.go
92 lines (75 loc) · 1.76 KB
/
habitica.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
package habitica
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
const (
baseURL = "https://habitica.com/api/v3"
UserAgent = "go-habitica/1" // 1 is the version
)
type HabiticaClient struct {
userID string
apiToken string
BaseURL string
UserAgent string
Client *http.Client
Tasks *TaskService
Tags *TagService
}
type ClientOpt func(*HabiticaClient)
func New(userID, apiToken string, opts ...ClientOpt) (*HabiticaClient, error) {
if len(userID) == 0 || len(apiToken) == 0 {
return nil, errors.New("needs valid user id and api token")
}
h := &HabiticaClient{
userID: userID,
apiToken: apiToken,
BaseURL: baseURL,
UserAgent: UserAgent,
Client: http.DefaultClient,
}
for _, o := range opts {
o(h)
}
h.Tasks = newTaskService(h)
h.Tags = newTagService(h)
return h, nil
}
func WithBaseURL(baseUrl string) func(*HabiticaClient) {
return func(h *HabiticaClient) {
h.BaseURL = baseUrl
}
}
func WithHttpClient(c *http.Client) func(*HabiticaClient) {
return func(h *HabiticaClient) {
h.Client = c
}
}
func (h *HabiticaClient) NewRequest(method, urlPath string, body interface{}) (*http.Request, error) {
url := fmt.Sprintf("%s/%s", h.BaseURL, urlPath)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, buf)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-user", h.userID)
req.Header.Set("x-api-key", h.apiToken)
return req, nil
}
func (h *HabiticaClient) Do(ctx context.Context, req *http.Request) (*http.Response, error) {
return h.Client.Do(req)
}