-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.go
98 lines (79 loc) · 2.02 KB
/
client.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
package mixin
import (
"context"
"fmt"
"strings"
"github.com/go-resty/resty/v2"
)
type Client struct {
Signer
Verifier
ClientID string
}
func NewFromKeystore(keystore *Keystore) (*Client, error) {
var auth *KeystoreAuth
var err error
if strings.Contains(keystore.PrivateKey, "RSA PRIVATE KEY") {
auth, err = AuthFromKeystore(keystore)
if err != nil {
return nil, fmt.Errorf("RSA keystore: %w", err)
}
} else if _, err := ed25519Encoding.DecodeString(keystore.PrivateKey); err == nil {
auth, err = AuthEd25519FromKeystore(keystore)
if err != nil {
return nil, fmt.Errorf("ed25519 keystore: %w", err)
}
} else {
return nil, fmt.Errorf("unexpected private key format")
}
c := &Client{
Signer: auth,
Verifier: NopVerifier(),
ClientID: keystore.ClientID,
}
return c, nil
}
func NewFromAccessToken(accessToken string) *Client {
c := &Client{
Signer: accessTokenAuth(accessToken),
Verifier: NopVerifier(),
}
return c
}
func NewFromOauthKeystore(keystore *OauthKeystore) (*Client, error) {
auth, err := AuthFromOauthKeystore(keystore)
if err != nil {
return nil, err
}
c := &Client{
Signer: auth,
Verifier: auth,
ClientID: keystore.ClientID,
}
return c, nil
}
func (c *Client) Request(ctx context.Context) *resty.Request {
ctx = WithVerifier(ctx, c.Verifier)
ctx = WithSigner(ctx, c.Signer)
return Request(ctx)
}
func (c *Client) Get(ctx context.Context, uri string, params map[string]string, resp interface{}) error {
r, err := c.Request(ctx).SetQueryParams(params).Get(uri)
if err != nil {
if requestID := extractRequestID(r); requestID != "" {
return WrapErrWithRequestID(err, requestID)
}
return err
}
return UnmarshalResponse(r, resp)
}
func (c *Client) Post(ctx context.Context, uri string, body interface{}, resp interface{}) error {
r, err := c.Request(ctx).SetBody(body).Post(uri)
if err != nil {
if requestID := extractRequestID(r); requestID != "" {
return WrapErrWithRequestID(err, requestID)
}
return err
}
return UnmarshalResponse(r, resp)
}