all repos

anpi @ e2e6e9e

yaml to anki importer

anpi/anki/http.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
add basic anki client, 1 year ago
1
package anki
2
3
import (
4
	"bytes"
5
	"encoding/json"
6
	"fmt"
7
	"net/http"
8
)
9
10
const (
11
	ankiURL            = "http://localhost:8765"
12
	ankiConnectVersion = 6
13
)
14
15
type AnkiResponse[T any] struct {
16
	Result T      `json:"result,omitempty"`
17
	Error  string `json:"error,omitempty"`
18
}
19
20
func (r AnkiResponse[T]) CheckErrors() error {
21
	if r.Error != "" {
22
		return fmt.Errorf("%s", r.Error)
23
	}
24
	return nil
25
}
26
27
type AnkiRequest[T any] struct {
28
	Action  string `json:"action"`
29
	Version int    `json:"version"`
30
	Params  T      `json:"params"`
31
}
32
33
type paramsDefault struct{}
34
35
func request[R any, P any](action string, params P) (AnkiResponse[R], error) {
36
	bodyReq, err := json.Marshal(AnkiRequest[P]{
37
		Action:  action,
38
		Version: ankiConnectVersion,
39
		Params:  params,
40
	})
41
	if err != nil {
42
		return AnkiResponse[R]{}, err
43
	}
44
45
	req, err := http.NewRequest(http.MethodGet, ankiURL, bytes.NewBuffer(bodyReq))
46
	if err != nil {
47
		return AnkiResponse[R]{}, err
48
	}
49
50
	req.Header.Set("Content-type", "application/json")
51
52
	client := &http.Client{}
53
	resp, err := client.Do(req)
54
	if err != nil {
55
		return AnkiResponse[R]{}, err
56
	}
57
58
	defer resp.Body.Close() //nolint
59
60
	var ankiResp AnkiResponse[R]
61
	if err := json.NewDecoder(resp.Body).Decode(&ankiResp); err != nil {
62
		return AnkiResponse[R]{}, err
63
	}
64
65
	return ankiResp, ankiResp.CheckErrors()
66
}