forked from bluesky-social/indigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxrpc.go
117 lines (98 loc) · 2.22 KB
/
xrpc.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package xrpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
type Client struct {
Client *http.Client
Auth *AuthInfo
Host string
}
func (c *Client) getClient() *http.Client {
if c.Client == nil {
return http.DefaultClient
}
return c.Client
}
type XRPCRequestType int
type AuthInfo struct {
AccessJwt string `json:"accessJwt"`
RefreshJwt string `json:"refreshJwt"`
Handle string `json:"handle"`
Did string `json:"did"`
DeclarationCid string `json:"declarationCid"`
}
const (
Query = XRPCRequestType(iota)
Procedure
)
func makeParams(p map[string]interface{}) string {
var parts []string
for k, v := range p {
parts = append(parts, fmt.Sprintf("%s=%s", k, url.QueryEscape(fmt.Sprint(v))))
}
return strings.Join(parts, "&")
}
func (c *Client) Do(ctx context.Context, kind XRPCRequestType, inpenc string, method string, params map[string]interface{}, bodyobj interface{}, out interface{}) error {
var body io.Reader
if bodyobj != nil {
if rr, ok := bodyobj.(io.Reader); ok {
body = rr
} else {
b, err := json.Marshal(bodyobj)
if err != nil {
return err
}
body = bytes.NewReader(b)
}
}
var m string
switch kind {
case Query:
m = "GET"
case Procedure:
m = "POST"
default:
return fmt.Errorf("unsupported request kind: %d", kind)
}
var paramStr string
if len(params) > 0 {
paramStr = "?" + makeParams(params)
}
req, err := http.NewRequest(m, c.Host+"/xrpc/"+method+paramStr, body)
if err != nil {
return err
}
if bodyobj != nil && inpenc != "" {
req.Header.Set("Content-Type", inpenc)
}
if c.Auth != nil {
req.Header.Set("Authorization", "Bearer "+c.Auth.AccessJwt)
}
resp, err := c.getClient().Do(req.WithContext(ctx))
if err != nil {
return err
}
if resp.StatusCode != 200 {
var i interface{}
_ = json.NewDecoder(resp.Body).Decode(&i)
fmt.Println("debug body response: ", i)
return fmt.Errorf("XRPC ERROR %d: %s", resp.StatusCode, resp.Status)
}
if out != nil {
if buf, ok := out.(*bytes.Buffer); ok {
io.Copy(buf, resp.Body)
} else {
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("decoding xrpc response: %w", err)
}
}
}
return nil
}