-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
112 lines (91 loc) · 2.46 KB
/
client.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
package anki
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"time"
)
const (
baseURL = "localhost"
basePort = 8765
minVersion = 6
)
// Client to connect to Anki.
type Client struct {
httpClient *http.Client
url string
minVersion int
httpContext context.Context
}
// NewClient returns a Client instance with the default URL.
func NewClient(url string) *Client {
return &Client{
httpClient: &http.Client{Timeout: time.Minute},
url: url,
minVersion: minVersion,
httpContext: context.TODO(),
}
}
// NewDefaultClient returns a Client instance with the default URL.
func NewDefaultClient() *Client {
url := fmt.Sprintf("http://%s:%s/", baseURL, strconv.Itoa(basePort))
return &Client{
httpClient: &http.Client{Timeout: time.Minute},
url: url,
minVersion: minVersion,
httpContext: context.TODO(),
}
}
// CheckVersion checks whether the AnkiConnect version is supported.
func (c *Client) CheckVersion() (bool, error) {
v, err := c.Version()
if err != nil {
return false, err
}
return v < c.minVersion, nil
}
func (c *Client) sendRequest(reqData ankiRequest, result interface{}) error {
body, err := json.Marshal(reqData)
if err != nil {
return err
}
req, err := http.NewRequest("POST", c.url, bytes.NewReader(body))
if err != nil {
return err
}
req = req.WithContext(c.httpContext)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes ankiResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Error)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
fullResponse := ankiResponse{
Result: result,
}
if err = json.NewDecoder(res.Body).Decode(&fullResponse); err != nil {
return err
}
return nil
}
type ankiRequest struct {
Action string `json:"action"` // The action to be performed by AnkiConnect
Version int `json:"version"` // Required AnkiConnect version
Params interface{} `json:"params"` // Request params
}
type ankiResponse struct {
Result interface{} `json:"result"` // Return value of the executed operation
Error string `json:"error"` // Null or description of any exception thrown during API execution
}