-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
70 lines (55 loc) · 1.46 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
package lambda
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
const apiGatewayServiceName = "execute-api"
type Signer interface {
SignHTTP(context.Context, aws.Credentials, *http.Request, string, string, string, time.Time, ...func(options *v4.SignerOptions)) error
}
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
// A Client makes HTTP requests to AWS Lambda functions
type Client struct {
cfg aws.Config
signer Signer
doer Doer
now func() time.Time
}
// New creates a Client for calling AWS Lambda functions
func New(cfg aws.Config, signer Signer, doer Doer, now func() time.Time) *Client {
return &Client{
cfg: cfg,
signer: signer,
doer: doer,
now: now,
}
}
// Do executes the HTTP request
func (c *Client) Do(req *http.Request) (*http.Response, error) {
hash := sha256.New()
if req.Body != nil {
var reqBody bytes.Buffer
if _, err := io.Copy(hash, io.TeeReader(req.Body, &reqBody)); err != nil {
return nil, err
}
req.Body = io.NopCloser(&reqBody)
}
encodedBody := hex.EncodeToString(hash.Sum(nil))
credentials, err := c.cfg.Credentials.Retrieve(req.Context())
if err != nil {
return nil, err
}
if err := c.signer.SignHTTP(req.Context(), credentials, req, encodedBody, apiGatewayServiceName, c.cfg.Region, c.now().UTC()); err != nil {
return nil, err
}
return c.doer.Do(req)
}