-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspot.go
50 lines (44 loc) · 1.17 KB
/
spot.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
package rest
import (
"context"
"fmt"
"log/slog"
"github.com/KarpelesLab/pjson"
)
// SpotClient is an interface fullfilled by spotlib.Client that contains
// everything we really care about, and helps avoid dependency loops
type SpotClient interface {
Query(ctx context.Context, target string, body []byte) ([]byte, error)
}
func SpotApply(ctx context.Context, client SpotClient, path, method string, param any, target any) error {
res, err := SpotDo(ctx, client, path, method, param)
if err != nil {
return err
}
err = pjson.UnmarshalContext(ctx, res.Data, target)
if Debug && err != nil {
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, res.Data), "event", "rest:not_json")
}
return err
}
func SpotDo(ctx context.Context, client SpotClient, path, method string, param any) (*Response, error) {
req := map[string]any{
"path": path,
"verb": method,
"params": param,
}
buf, err := pjson.Marshal(req)
if err != nil {
return nil, err
}
respbuf, err := client.Query(ctx, "@/p_api", buf)
if err != nil {
return nil, err
}
var resp *Response
err = pjson.Unmarshal(respbuf, &resp)
if err != nil {
return nil, err
}
return resp, nil
}