-
Notifications
You must be signed in to change notification settings - Fork 560
/
Copy pathresponse.go
89 lines (72 loc) · 2.08 KB
/
response.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
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package cfn
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil" //nolint: staticcheck
"log"
"net/http"
)
// StatusType represents a CloudFormation response status
type StatusType string
const (
StatusSuccess StatusType = "SUCCESS"
StatusFailed StatusType = "FAILED"
)
// Response is a representation of a Custom Resource
// response expected by CloudFormation.
type Response struct {
Status StatusType `json:"Status"`
RequestID string `json:"RequestId"`
LogicalResourceID string `json:"LogicalResourceId"`
StackID string `json:"StackId"`
PhysicalResourceID string `json:"PhysicalResourceId"`
Reason string `json:"Reason,omitempty"`
NoEcho bool `json:"NoEcho,omitempty"`
Data map[string]interface{} `json:"Data,omitempty"`
url string
}
// NewResponse creates a Response with the relevant verbatim copied
// data from a Event
func NewResponse(r *Event) *Response {
return &Response{
RequestID: r.RequestID,
LogicalResourceID: r.LogicalResourceID,
StackID: r.StackID,
url: r.ResponseURL,
}
}
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
func (r *Response) sendWith(client httpClient) error {
body, err := json.Marshal(r)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPut, r.url, bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Del("Content-Type")
res, err := client.Do(req)
if err != nil {
return err
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
res.Body.Close()
if res.StatusCode != 200 {
log.Printf("StatusCode: %d\nBody: %v\n", res.StatusCode, string(body))
return fmt.Errorf("invalid status code. got: %d", res.StatusCode)
}
return nil
}
// Send will send the Response to the given URL using the
// default HTTP client
func (r *Response) Send() error {
return r.sendWith(http.DefaultClient)
}