/
start.go
67 lines (58 loc) · 1.75 KB
/
start.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
package golambda
import (
"context"
"encoding/json"
"github.com/aws/aws-lambda-go/lambda"
"github.com/nguyengg/golambda/configsupport"
"github.com/nguyengg/golambda/logsupport"
"github.com/nguyengg/golambda/metrics"
"github.com/nguyengg/golambda/start"
"log"
)
// StartHandlerFunc calls lambda.StartHandlerFunc passing the given handler after wrapping the context with a metrics
// instance that is used to populate basis statistics about the invocation.
//
// Use this wrapper if there isn't one created for specific events.
func StartHandlerFunc[TIn any, TOut any, H lambda.HandlerFunc[TIn, TOut]](handler H, options ...start.Option) {
opts := start.New(options)
lambda.StartHandlerFunc(func(ctx context.Context, in TIn) (out TOut, err error) {
m := metrics.NewSimpleMetricsContext(
opts.LoggerProvider(ctx).WithContext(ctx),
"",
0)
ctx = m.WithContext(ctx)
if !opts.DisableSetUpGlobalLogger {
defer logsupport.SetUpGlobalLogger(ctx)()
}
if !opts.DisableRequestDebugLogging && configsupport.IsDebug() {
data, err := json.Marshal(in)
if err != nil {
log.Printf("ERROR marshal request: %v\n", err)
} else {
log.Printf("INFO request: %s\n", data)
}
}
if !opts.DisableResponseDebugLogging && configsupport.IsDebug() {
defer func() {
data, err := json.Marshal(out)
if err != nil {
log.Printf("ERROR marshal response: %v\n", err)
} else {
log.Printf("INFO response: %s\n", data)
}
}()
}
defer func() {
switch r := recover(); {
case r != nil:
log.Printf("ERROR handler panicked with error: %#v", r)
m.Panicked()
case err != nil:
log.Printf("ERROR handler failed with error: %#v", err)
m.Faulted()
}
m.Log()
}()
return handler(ctx, in)
}, opts.HandlerOptions...)
}