This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse_lambda.go
100 lines (80 loc) · 1.96 KB
/
response_lambda.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
90
91
92
93
94
95
96
97
98
99
100
package golam
import (
"bytes"
"encoding/base64"
"github.com/aws/aws-lambda-go/events"
"io/ioutil"
"net/http"
)
var _ ResponseAdapter = (*responseLambdaAdapter)(nil)
func NewResponseLambdaAdapter(response *events.APIGatewayV2HTTPResponse) ResponseAdapter {
return &responseLambdaAdapter{
header: make(http.Header),
response: response,
}
}
type responseLambdaAdapter struct {
header http.Header
buffer bytes.Buffer
response *events.APIGatewayV2HTTPResponse
}
func (w *responseLambdaAdapter) Header() http.Header {
return w.header
}
func (w *responseLambdaAdapter) Write(bytes []byte) (int, error) {
return w.buffer.Write(bytes)
}
func (w *responseLambdaAdapter) WriteHeader(statusCode int) {
w.response.StatusCode = statusCode
}
func (w *responseLambdaAdapter) SetCookie(cookie *http.Cookie) {
v := cookie.String()
if len(v) == 0 {
return
}
w.setCookies(v)
}
func (w *responseLambdaAdapter) setCookies(v ...string) {
w.response.Cookies = append(w.response.Cookies, v...)
}
func (w *responseLambdaAdapter) Commit() error {
return w.commit()
}
func (w *responseLambdaAdapter) commit() error {
if w.response.StatusCode == 0 {
w.response.StatusCode = http.StatusOK
}
body, err := ioutil.ReadAll(&w.buffer)
if err != nil {
return err
}
w.response.IsBase64Encoded = w.isBinary()
if w.response.IsBase64Encoded {
w.response.Body = base64.StdEncoding.EncodeToString(body)
} else {
w.response.Body = string(body)
}
w.response.Headers = make(map[string]string)
w.response.MultiValueHeaders = make(map[string][]string)
for k, v := range w.header {
// known-headers
switch k {
case HeaderSetCookie:
w.setCookies(v...)
continue
}
if len(v) == 1 {
w.response.Headers[k] = v[0]
} else {
w.response.MultiValueHeaders[k] = v
}
}
return nil
}
func (w *responseLambdaAdapter) isBinary() bool {
contentType := w.header.Get(HeaderContentType)
if len(contentType) == 0 {
return false
}
return !notBinaryTable[contentType]
}