summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--add.go59
-rw-r--r--main.go49
2 files changed, 61 insertions, 47 deletions
diff --git a/add.go b/add.go
new file mode 100644
index 0000000..40c45ee
--- /dev/null
+++ b/add.go
@@ -0,0 +1,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
+}
diff --git a/main.go b/main.go
index c1dd369..ea0f382 100644
--- a/main.go
+++ b/main.go
@@ -3,9 +3,6 @@
package main
import (
- "bytes"
- "encoding/json"
- "io"
"log"
"net/http"
"os"
@@ -82,49 +79,7 @@ func main() {
c := http.DefaultClient
c.Timeout = 5 * time.Second
- // Create the card
- noteRequest := addNote{
- Action: "addNote",
- Version: 6,
- Params: addNoteParams{
- Note: note{
- DeckName: deckName,
- ModelName: modelName,
- Fields: fields{
- Front: word,
- Back: definition,
- },
- Options: options{
- AllowDuplicate: false,
- DuplicateScope: "deck",
- },
- },
- },
+ if err := addCard(c, word, definition); err != nil {
+ log.Fatalf("creating card: %s", err)
}
-
- jsonBytes, err := json.Marshal(noteRequest)
- if err != nil {
- log.Fatalf("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 {
- log.Fatalf("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 != "" {
- log.Fatalf("creating card: %s", jsonResp.Error)
- }
-
}