-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda.go
83 lines (66 loc) · 2.03 KB
/
lambda.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
package secret
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/aws/aws-sdk-go-v2/service/lambda"
"gopkg.in/yaml.v3"
)
/*
export DB_URI=aws-lambda:us-east-1:parameters,parameter,mongodb,body:uri
# Function: parameters
# Request: {"parameter":"mongodb"}
# Response field: body
# Response: {"statusCode": 200,"body": "{\"uri\": \"mongodb://localhost:27017/?retryWrites=false\"}"}
*/
func queryLambda(getAwsConfig awsConfigSolver, dynamoOptions string) (string, error) {
const me = "queryLambda"
options := strings.SplitN(dynamoOptions, ",", 4)
if len(options) < 4 {
return "", fmt.Errorf("%s: bad dynamodb options, expecting 4 fields - got: '%s'",
me, dynamoOptions)
}
functionName := options[0]
keyName := options[1]
keyValue := options[2]
responseField := options[3]
request := fmt.Sprintf(`{"%s":"%s"}`, keyName, keyValue)
requestBytes := []byte(request)
awsConfig, errAwsConfig := getAwsConfig.get()
if errAwsConfig != nil {
return "", errAwsConfig
}
clientLambda := lambda.NewFromConfig(awsConfig)
input := &lambda.InvokeInput{
FunctionName: &functionName,
Payload: requestBytes,
}
resp, errInvoke := clientLambda.Invoke(context.TODO(), input)
if errInvoke != nil {
return "", errInvoke
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%s: Invoke lambda function=%s bad status=%d payload: %s",
me, functionName, resp.StatusCode, resp.Payload)
}
var funcError string
if resp.FunctionError != nil {
funcError = *resp.FunctionError
}
if funcError != "" {
return "", fmt.Errorf("%s: Invoke lambda function=%s function_error='%s' payload: %s",
me, functionName, funcError, resp.Payload)
}
payload := map[string]string{}
errUnmarshal := yaml.Unmarshal(resp.Payload, &payload)
if errUnmarshal != nil {
return "", errUnmarshal
}
response, found := payload[responseField]
if !found {
return "", fmt.Errorf("%s: Invoke lambda function=%s: missing response field: '%s': %s",
me, functionName, responseField, resp.Payload)
}
return response, nil
}