This repository has been archived by the owner on Mar 16, 2023. It is now read-only.
/
http.go
71 lines (58 loc) · 1.66 KB
/
http.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
/*
Package zink implements the functions to access z.umn.edu.
*/
package zink
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
"github.com/pkg/errors"
)
// Handle holds the access ID and secret key.
type Handle struct {
AccessID string
SecretKey string
AccessPoint string
}
const DefaultAccessPoint = "https://z.umn.edu/api/v1/urls"
// New creates a new Handle.
func New(id string, secret string) *Handle {
return &Handle{
AccessID: id,
SecretKey: secret,
AccessPoint: DefaultAccessPoint,
}
}
// Do sends the requets to the access point.
func (h *Handle) Do(ctx context.Context, reqs ...Request) ([]Response, error) {
payload := jwt.New()
if err := payload.Set("urls", reqs); err != nil {
return nil, errors.Wrapf(err, "failed to prepare the jwt payload")
}
token, err := jwt.Sign(payload, jwa.HS256, []byte(h.SecretKey))
if err != nil {
return nil, errors.Wrapf(err, "failed to sign the jwt payload")
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, h.AccessPoint, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to prepare the HTTP request")
}
httpReq.Header.Set("Authorization", fmt.Sprintf("%s:%s", h.AccessID, token))
resp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, errors.Wrapf(err, "failed to make the HTTP request")
}
defer resp.Body.Close()
var rawRes []rawResponse
if err = json.NewDecoder(resp.Body).Decode(&rawRes); err != nil {
return nil, errors.Wrapf(err, "failed to decode the HTTP response")
}
res, err := parseRawResponses(rawRes)
if err != nil {
return nil, err
}
return res, nil
}