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
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const apiVersion = 6
func addCard(c *http.Client, front, back string) error {
noteRequest := addNote{
Action: "addNote",
Version: apiVersion,
Params: addNoteParams{
Note: note{
DeckName: deckName,
ModelName: modelName,
Fields: fields{
Front: front,
Back: back,
},
Options: options{
AllowDuplicate: false,
DuplicateScope: "deck",
},
},
},
}
jsonBytes, err := json.Marshal(noteRequest)
if err != nil {
return fmt.Errorf("marshaling JSON: %s", err)
}
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonBytes))
req.Header.Set("Content-Type", "application/json")
resp, err := c.Do(req)
if err != nil {
return fmt.Errorf("making request: %s", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var jsonResp struct {
Error string `json:"error"`
}
json.Unmarshal(body, &jsonResp)
if jsonResp.Error != "" {
return fmt.Errorf("creating card: %s", jsonResp.Error)
}
return nil
}
|