-
Notifications
You must be signed in to change notification settings - Fork 1
/
apigw_handler.go
170 lines (145 loc) · 4.27 KB
/
apigw_handler.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package g8
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/google/uuid"
newrelic "github.com/newrelic/go-agent"
"github.com/newrelic/go-agent/_integrations/nrlambda"
"github.com/rs/zerolog"
)
type APIGatewayProxyContext struct {
Context context.Context
Request events.APIGatewayProxyRequest
Response events.APIGatewayProxyResponse
Logger zerolog.Logger
NewRelicTx newrelic.Transaction
CorrelationID string
}
type APIGatewayProxyHandlerFunc func(c *APIGatewayProxyContext) error
func APIGatewayProxyHandler(
h APIGatewayProxyHandlerFunc,
conf HandlerConfig,
) func(context.Context, events.APIGatewayProxyRequest) (any, error) {
return func(ctx context.Context, r events.APIGatewayProxyRequest) (any, error) {
correlationID := getCorrelationIDAPIGW(r.Headers)
logger := configureLogger(conf).
Str("route", r.RequestContext.ResourcePath).
Str("correlation_id", correlationID).
Logger()
c := &APIGatewayProxyContext{
Context: ctx,
Request: r,
Logger: logger,
NewRelicTx: newrelic.FromContext(ctx),
CorrelationID: correlationID,
}
if c.Response.Headers == nil {
c.Response.Headers = make(map[string]string)
}
c.Response.Headers[headerCorrelationID] = correlationID
c.Response.Headers[headerBuildVersion] = conf.BuildVersion
c.AddNewRelicAttribute("functionName", conf.FunctionName)
c.AddNewRelicAttribute("route", r.RequestContext.ResourcePath)
c.AddNewRelicAttribute("correlationID", correlationID)
c.AddNewRelicAttribute("buildVersion", conf.BuildVersion)
err := h(c)
if err != nil {
c.handleError(err)
return c.Response, nil
}
return c.Response, nil
}
}
func APIGatewayProxyHandlerWithNewRelic(h APIGatewayProxyHandlerFunc, conf HandlerConfig) lambda.Handler {
return nrlambda.Wrap(APIGatewayProxyHandler(h, conf), conf.NewRelicApp)
}
func (c *APIGatewayProxyContext) Bind(v interface{}) error {
if err := json.Unmarshal([]byte(c.Request.Body), v); err != nil {
return ErrInvalidBody
}
if validatable, ok := v.(Validatable); ok {
err := validatable.Validate()
if err != nil {
return err
}
}
return nil
}
func (c *APIGatewayProxyContext) JSON(statusCode int, body interface{}) error {
var b []byte
var err error
if body != nil {
b, err = json.Marshal(body)
if err != nil {
return err
}
if c.Response.Headers == nil {
c.Response.Headers = make(map[string]string)
}
c.Response.Headers["Content-Type"] = "application/json"
}
c.Response.StatusCode = statusCode
c.Response.Body = string(b)
return nil
}
func (c *APIGatewayProxyContext) AddNewRelicAttribute(key string, val interface{}) {
if c.NewRelicTx == nil {
return
}
if err := c.NewRelicTx.AddAttribute(key, val); err != nil {
c.Logger.Error().Msgf("failed to add attr '%s' to new relic tx: %+v", key, err)
}
}
func (c *APIGatewayProxyContext) handleError(err error) {
var newErr Err
switch err := err.(type) {
case Err:
newErr = err
default:
newErr = ErrInternalServer
logUnhandledError(c.Logger, err)
}
_ = c.JSON(newErr.Status, newErr)
}
// GetCookie retrieves the cookie with the given name
func (c *APIGatewayProxyContext) GetCookie(name string) (http.Cookie, bool) {
rawCookies := c.GetHeader("cookie")
if rawCookies == "" {
return http.Cookie{}, false
}
rawRequest := fmt.Sprintf("GET / HTTP/1.0\r\nCookie: %s\r\n\r\n", rawCookies)
req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(rawRequest)))
if err != nil {
return http.Cookie{}, false
}
for _, cookie := range req.Cookies() {
if cookie.Name == name {
return *cookie, true
}
}
return http.Cookie{}, false
}
// GetHeader retrieves the header value by name. It canonicalizes headers to ensure that values can be accessed
// in a case insensitive manner
func (c *APIGatewayProxyContext) GetHeader(name string) string {
canonicalHeaders := http.Header{}
for k, v := range c.Request.MultiValueHeaders {
for _, value := range v {
canonicalHeaders.Add(k, value)
}
}
return canonicalHeaders.Get(name)
}
func getCorrelationIDAPIGW(headers map[string]string) string {
correlationID := headers[headerCorrelationID]
if correlationID != "" {
return correlationID
}
return uuid.New().String()
}