-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggl.go
74 lines (62 loc) · 1.5 KB
/
toggl.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
type Project struct {
Id int `json:"id"`
Name string `json:"name"`
}
func sendTimeEntries(entries []TimeEntry) {
for _, entry := range entries {
sendTimeEntry(&entry)
}
}
func sendTimeEntry(entry *TimeEntry) {
entryJson, err := json.Marshal(entry)
if err != nil {
println("error: " + err.Error())
return
}
var jsonStr = "{\"time_entry\":" + string(entryJson) + "}"
sendApiRequest("POST", "/time_entries", jsonStr)
}
func getProjects() []Project {
configuration := getConfiguration()
response := sendApiRequest("GET", "/workspaces/"+configuration.WorkspaceId+"/projects", "")
var projects []Project
err := json.Unmarshal([]byte(response), &projects)
if err != nil {
fmt.Println("error:", err)
}
return projects
}
func sendApiRequest(method, togglRelativeUrl, jsonBody string) string {
configuration := getConfiguration()
url := "https://www.toggl.com/api/v8" + togglRelativeUrl
req, err := http.NewRequest(method, url, bytes.NewBufferString(jsonBody))
if err != nil {
println("error: " + err.Error())
return ""
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(configuration.ApiToken, "api_token")
var client = http.Client{}
resp, err := client.Do(req)
if err != nil {
println("error: " + err.Error())
return ""
}
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
body := buf.String()
if resp.StatusCode != 200 {
println(resp.Status)
println(body)
os.Exit(1)
}
return body
}