-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapi.go
More file actions
80 lines (65 loc) · 1.83 KB
/
api.go
File metadata and controls
80 lines (65 loc) · 1.83 KB
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
package yaakcli
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/pterm/pterm"
)
func NewAPIRequest(method, path string, body io.Reader) *http.Request {
baseURL := prodStagingDevStr("https://api.yaak.app", "https://todo.yaak.app", "http://localhost:9444")
req, err := http.NewRequest(method, baseURL+"/api/v1"+path, body)
if err != nil {
pterm.Error.Printf("Failed to create API request: %s\n", err)
os.Exit(1)
}
return req
}
var YaakHttpClient = http.Client{Timeout: 10 * time.Second, Transport: &yaakTransport{base: http.DefaultTransport}}
type yaakTransport struct {
base http.RoundTripper
}
func (t *yaakTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Set("User-Agent", fmt.Sprintf("YaakCli/%s (%s)", CLIVersion, GetUAPlatform()))
return t.base.RoundTrip(r)
}
func SendAPIRequest(r *http.Request) []byte {
found, token, err := getAuthToken()
if err != nil {
ExitError(err.Error())
} else if !found {
pterm.Warning.Println("Not logged in")
pterm.Info.Println("Please run `yaakcli login`")
os.Exit(1)
}
r.Header.Set("X-Yaak-Session", token)
r.Header.Set("User-Agent", fmt.Sprintf("YaakCli/%s (%s)", CLIVersion, GetUAPlatform()))
resp, err := YaakHttpClient.Do(r)
CheckError(err)
defer func(Body io.ReadCloser) {
CheckError(Body.Close())
}(resp.Body)
body, err := io.ReadAll(resp.Body)
CheckError(err)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var apiErr APIError
err = json.Unmarshal(body, &apiErr)
if err != nil {
pterm.Error.Printf("API Error %d → %s\n", resp.StatusCode, body)
} else {
pterm.Error.Println(apiErr.Message)
}
os.Exit(1)
}
message := resp.Header.Get("X-Cli-Message")
if message != "" {
pterm.Info.Printf(message)
}
return body
}
type APIError struct {
Error string `json:"error"`
Message string `json:"message"`
}