-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.go
More file actions
87 lines (73 loc) · 2.33 KB
/
handler.go
File metadata and controls
87 lines (73 loc) · 2.33 KB
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
package lambada
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/aws/aws-lambda-go/lambda"
)
// LambadaHandler is a Lambada lambda handler function which can be used with lambda.Start.
type LambadaHandler func(ctx context.Context, req Request) (Response, error)
// NewHandler returns a Lambda function handler which can be used with lambda.Start.
// The returned lambda handler wraps incoming requets into http.Request, calls the provided http.Handler and converts
// the response into an API Gateway response.
func NewHandler(h http.Handler, options ...Option) LambadaHandler {
opts := newOptions(options...)
return func(ctx context.Context, req Request) (Response, error) {
defer func() {
if r := recover(); r != nil {
opts.logger.LogPanic(ctx, &req, r)
// Forward panic
panic(r)
}
}()
if req.Version == "2.0" {
req.version = 2
} else {
req.version = 1
}
opts.logger.LogRequest(ctx, &req)
w := newResponseWriter(opts.outputMode, opts.defaultBinary)
// Find out which version it is
var httpRequest *http.Request
var err error
if req.version == 2 {
httpRequest, err = makeV2Request(ctx, &req)
} else {
httpRequest, err = makeV1Request(ctx, &req)
}
if err != nil {
opts.logger.LogError(ctx, &req, err)
return Response{}, err
}
// Let the handler process the request
h.ServeHTTP(w, httpRequest)
w.finalize()
res := Response{
StatusCode: w.statusCode,
Headers: toSingleValueHeaders(w.lockedHeader),
MultiValueHeaders: w.lockedHeader,
Body: bytesToBody(w.body.Bytes(), w.binary),
IsBase64Encoded: w.binary,
}
opts.logger.LogResponse(ctx, &req, &res)
return res, nil
}
}
// Serve starts the Lambda handler using the http.Handler to serve incoming requests.
// Serve calls lambda.Start(NewHandler(h)) under the hood.
func Serve(h http.Handler) {
ServeWithOptions(h)
}
// ServeWithOptions starts the lambda handler using the http.Handler and options to serve incoming requests.
// ServeWithOptions calls lambda.Start(NewHandler(h, options...)) under the hood.
func ServeWithOptions(h http.Handler, options ...Option) {
lambda.Start(NewHandler(h, options...))
}
func marshalJSON(v any) string {
data, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf("<failed to marshal json: %v>", err)
}
return string(data)
}