This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_response.go
78 lines (67 loc) · 2.37 KB
/
proxy_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
package xlambda
import (
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/gofor-little/log"
)
// ProxyResponseHTML builds an API gateway proxy response where the body's content type is text/html.
// statusCode should be a valid HTTP status code.
// If err is nil no error will be returned.
// If data is nil nothing will be written to the response body.
func ProxyResponseHTML(statusCode int, err error, data interface{}) (*events.APIGatewayProxyResponse, error) {
if err != nil {
log.Error(log.Fields{
"error": err,
"message": "api request failed",
"statusCode": statusCode,
})
}
response := &events.APIGatewayProxyResponse{
Headers: map[string]string{
"Content-Type": "text/html",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent",
"Access-Control-Allow-Origin": accessControlAllowOrigin,
"Access-Control-Allow-Methods": "OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD",
},
StatusCode: statusCode,
}
if data != nil {
response.Body = fmt.Sprintf("%s", data)
}
return response, nil
}
// ProxyResponseJSON builds an API gateway proxy response where the body's content type is application/json.
// statusCode should be a valid HTTP status code.
// If err is nil no error will be returned.
// If data is nil nothing will be written to the response body.
func ProxyResponseJSON(statusCode int, err error, data interface{}) (*events.APIGatewayProxyResponse, error) {
if err != nil {
log.Error(log.Fields{
"error": err,
"message": "api request failed",
"statusCode": statusCode,
})
}
response := &events.APIGatewayProxyResponse{
Headers: map[string]string{
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent",
"Access-Control-Allow-Origin": accessControlAllowOrigin,
"Access-Control-Allow-Methods": "OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD",
},
StatusCode: statusCode,
}
if data != nil {
body, marshalErr := json.Marshal(data)
if marshalErr != nil {
log.Error(log.Fields{
"error": fmt.Errorf("failed to marshal response body and API request failed: %w", marshalErr),
"statusCode": statusCode,
})
return response, nil
}
response.Body = string(body)
}
return response, nil
}