-
Notifications
You must be signed in to change notification settings - Fork 6
/
todoist.go
117 lines (96 loc) · 2.52 KB
/
todoist.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package todoist
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// Token save the personal token from todoist
var Token string
var todoistURL = "https://api.todoist.com/rest/v1/"
func makeRequest(method, endpoint string, data interface{}) (*http.Response, error) {
url := todoistURL + endpoint
body := bytes.NewBuffer([]byte{})
if data != nil {
json, err := json.Marshal(data)
if err != nil {
return nil, err
}
body = bytes.NewBuffer(json)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
bearer := fmt.Sprintf("Bearer %s", Token)
req.Header.Add("Authorization", bearer)
if data != nil {
req.Header.Add("Content-Type", "application/json")
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= 400 {
defer res.Body.Close()
str, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf(string(str))
}
return res, nil
}
type taskSave struct {
Content string `json:"content"`
ProjectID int `json:"project_id,omitempty"`
Order int `json:"order,omitempty"`
LabelIDs []int `json:"label_ids,omitempty"`
Priority int `json:"priority,omitempty"`
DueString string `json:"due_string,omitempty"`
DueDateTime time.Time `json:"due_datetime,omitempty"`
DueLang string `json:"due_lang,omitempty"`
}
func (ts taskSave) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString("{")
if ts.Content == "" {
return nil, fmt.Errorf("Content is empty")
}
buffer.WriteString(fmt.Sprintf("\"content\":\"%s\"", ts.Content))
if ts.ProjectID != 0 {
buffer.WriteString(fmt.Sprintf(",\"project_id\":%d", ts.ProjectID))
}
if ts.Order != 0 {
buffer.WriteString(fmt.Sprintf(",\"order\":%d", ts.Order))
}
if !ts.DueDateTime.IsZero() {
buffer.WriteString(",\"due_datetime\":")
json, err := json.Marshal(ts.DueDateTime)
if err != nil {
return nil, err
}
buffer.Write(json)
}
if len(ts.LabelIDs) != 0 {
buffer.WriteString(",\"label_ids\":")
json, err := json.Marshal(ts.LabelIDs)
if err != nil {
return nil, err
}
buffer.Write(json)
}
if ts.Priority != 0 {
buffer.WriteString(fmt.Sprintf(",\"priority\":%d", ts.Priority))
}
if ts.DueString != "" {
buffer.WriteString(fmt.Sprintf(",\"due_string\":\"%s\"", ts.DueString))
}
if ts.DueLang != "" {
buffer.WriteString(fmt.Sprintf(",\"due_lang\":\"%s\"", ts.DueLang))
}
buffer.WriteString("}")
return buffer.Bytes(), nil
}