sync.go (948B)
1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "net/http" 9 10 tea "github.com/charmbracelet/bubbletea" 11 ) 12 13 func syncWithAnkiWeb(c *http.Client, apiURL string) tea.Cmd { 14 return func() tea.Msg { 15 jsonBytes, err := json.Marshal(struct { 16 Action string `json:"action"` 17 Version int `json:"version"` 18 }{ 19 "sync", apiVersion, 20 }) 21 if err != nil { 22 return errMsg(fmt.Errorf("marshaling JSON: %s", err)) 23 } 24 25 req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonBytes)) 26 req.Header.Set("Content-Type", "application/json") 27 28 resp, err := c.Do(req) 29 if err != nil { 30 return errMsg(fmt.Errorf("making request: %s", err)) 31 } 32 defer resp.Body.Close() 33 34 body, _ := io.ReadAll(resp.Body) 35 36 var jsonResp struct { 37 Error string `json:"error"` 38 } 39 40 json.Unmarshal(body, &jsonResp) 41 if jsonResp.Error != "" { 42 return errMsg(fmt.Errorf("creating card: %s", jsonResp.Error)) 43 } 44 45 return syncedMsg(true) 46 } 47 }