-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmint.go
More file actions
101 lines (87 loc) · 2.25 KB
/
mint.go
File metadata and controls
101 lines (87 loc) · 2.25 KB
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
package cli
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strings"
"github.com/spolu/settle/lib/client"
"github.com/spolu/settle/lib/errors"
"github.com/spolu/settle/lib/svc"
"github.com/spolu/settle/mint"
)
// Mint represents a mint
type Mint struct {
Host string
Credentials *Credentials
}
// MintFromContextCredentials returns a mint object from the credentials stored
// in the current context.
func MintFromContextCredentials(
ctx context.Context,
) (*Mint, error) {
c := GetCredentials(ctx)
if c == nil {
return nil, errors.Trace(
errors.Newf("Not logged in (see `settle login`)"))
}
return &Mint{
Host: c.Host,
Credentials: c,
}, nil
}
// Post performs a POST request to the mint.
func (m *Mint) Post(
ctx context.Context,
path string,
query url.Values,
params url.Values,
) (*int, *svc.Resp, error) {
req, err := http.NewRequest("POST",
mint.FullMintURL(ctx, m.Host, path, query).String(),
strings.NewReader(params.Encode()))
if err != nil {
return nil, nil, errors.Trace(err)
}
req.Header.Add("Mint-Protocol-Version", mint.ProtocolVersion)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if m.Credentials != nil {
req.SetBasicAuth(m.Credentials.Username, m.Credentials.Password)
}
r, err := client.Default(ctx).Do(req)
if err != nil {
return nil, nil, errors.Trace(err)
}
defer r.Body.Close()
var raw svc.Resp
if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
return nil, nil, errors.Trace(err)
}
return &r.StatusCode, &raw, nil
}
// Get performs a GET request to the mint.
func (m *Mint) Get(
ctx context.Context,
path string,
query url.Values,
) (*int, *svc.Resp, error) {
req, err := http.NewRequest("GET",
mint.FullMintURL(ctx, m.Host, path, query).String(), nil)
if err != nil {
return nil, nil, errors.Trace(err)
}
req.Header.Add("Mint-Protocol-Version", mint.ProtocolVersion)
if m.Credentials != nil {
req.SetBasicAuth(m.Credentials.Username, m.Credentials.Password)
}
r, err := client.Default(ctx).Do(req)
if err != nil {
return nil, nil, errors.Trace(err)
}
defer r.Body.Close()
var raw svc.Resp
if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
return nil, nil, errors.Trace(err)
}
return &r.StatusCode, &raw, nil
}