-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprint_response.go
72 lines (56 loc) · 1.66 KB
/
print_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
package main
import (
"encoding/json"
"fmt"
"log/slog"
"strings"
"github.com/aws/aws-lambda-go/lambda/messages"
)
func printResponse(
logger *slog.Logger,
invokeResponse messages.InvokeResponse,
parseJSON bool,
) error {
logger.Debug("Handling lambda event response")
if invokeResponse.Error != nil {
var builder strings.Builder
builder.WriteString(fmt.Sprintf("Returned error: %s\n", invokeResponse.Error.Message))
builder.WriteString("\nStack trace:\n")
for _, detail := range invokeResponse.Error.StackTrace {
builder.WriteString(fmt.Sprintf("%s:%d - %s\n", detail.Path, detail.Line, detail.Label))
}
logger.Error("Lambda returned error:\n" + builder.String())
}
if invokeResponse.Payload == nil {
logger.Debug("Lambda returned no payload")
return nil
}
response := make(map[string]any)
if err := json.Unmarshal(invokeResponse.Payload, &response); err != nil {
logger.Info("Lambda returned non-JSON payload:\n" + string(invokeResponse.Payload))
return nil //nolint:nilerr
}
if parseJSON {
response = parseInnerJSON(response)
}
out, err := json.MarshalIndent(response, "", " ")
if err != nil {
return fmt.Errorf("[in lambdalocal.printResponse] MarshalIndent response failed: %w", err)
}
logger.Info("Lambda returned JSON payload:\n" + string(out))
return nil
}
// parseInnerJSON walks all key value pairs on response and attempt to unmarshal
// strings to JSON.
func parseInnerJSON(data map[string]any) map[string]any {
for k, v := range data {
if vv, ok := v.(string); ok {
newJSON := any(nil)
if err := json.Unmarshal([]byte(vv), &newJSON); err != nil {
continue
}
data[k] = newJSON
}
}
return data
}