-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathiam_handle.go
70 lines (60 loc) · 1.67 KB
/
iam_handle.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 iamutil
import (
"context"
"encoding/json"
"net/http"
"github.com/hashicorp/errwrap"
"google.golang.org/api/googleapi"
)
type IamHandle struct {
c *http.Client
userAgent string
}
func GetIamHandle(client *http.Client, userAgent string) *IamHandle {
return &IamHandle{
c: client,
userAgent: userAgent,
}
}
func (h *IamHandle) GetIamPolicy(ctx context.Context, r IamResource) (*Policy, error) {
req, err := r.GetIamPolicyRequest()
if err != nil {
return nil, errwrap.Wrapf("unable to construct GetIamPolicy request: {{err}}", err)
}
var p Policy
if err := h.doRequest(ctx, req, &p); err != nil {
return nil, errwrap.Wrapf("unable to get policy: {{err}}", err)
}
return &p, nil
}
func (h *IamHandle) SetIamPolicy(ctx context.Context, r IamResource, p *Policy) (*Policy, error) {
req, err := r.SetIamPolicyRequest(p)
if err != nil {
return nil, errwrap.Wrapf("unable to construct SetIamPolicy request: {{err}}", err)
}
var out Policy
if err := h.doRequest(ctx, req, &out); err != nil {
return nil, errwrap.Wrapf("unable to set policy: {{err}}", err)
}
return &out, nil
}
func (h *IamHandle) doRequest(ctx context.Context, req *http.Request, out interface{}) error {
if req.Header == nil {
req.Header = make(http.Header)
}
if h.userAgent != "" {
req.Header.Set("User-Agent", h.userAgent)
}
resp, err := h.c.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer googleapi.CloseBody(resp)
if err := googleapi.CheckResponse(resp); err != nil {
return err
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return errwrap.Wrapf("unable to decode JSON resp to output interface: {{err}}", err)
}
return nil
}