Lambda-Promtail (#2282)

* specs out lambda-promtail

* init fn

* udpates readme/template

* lambda-promtail docs

* lambda promtail includes source timestamp and uses context

* non markdown links

* new doc structure
pull/2450/head
Owen Diehl 5 years ago committed by GitHub
parent d93b410a93
commit 2a596a77d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      .gitignore
  2. 4
      CHANGELOG.md
  3. 7
      docs/sources/clients/_index.md
  4. 84
      docs/sources/clients/lambda-promtail/_index.md
  5. 1
      go.mod
  6. 4
      go.sum
  7. 15
      tools/lambda-promtail/Makefile
  8. 120
      tools/lambda-promtail/README.md
  9. 102
      tools/lambda-promtail/lambda-promtail/main.go
  10. 61
      tools/lambda-promtail/template.yaml
  11. 203
      vendor/github.com/aws/aws-lambda-go/LICENSE
  12. 15
      vendor/github.com/aws/aws-lambda-go/LICENSE-LAMBDACODE
  13. 7
      vendor/github.com/aws/aws-lambda-go/LICENSE-SUMMARY
  14. 49
      vendor/github.com/aws/aws-lambda-go/events/README.md
  15. 38
      vendor/github.com/aws/aws-lambda-go/events/README_ALBTargetGroupEvents.md
  16. 67
      vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayCustomAuthorizer.md
  17. 36
      vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayEvent.md
  18. 21
      vendor/github.com/aws/aws-lambda-go/events/README_AutoScaling.md
  19. 67
      vendor/github.com/aws/aws-lambda-go/events/README_Chime_Bots.md
  20. 17
      vendor/github.com/aws/aws-lambda-go/events/README_CloudWatch_Events.md
  21. 20
      vendor/github.com/aws/aws-lambda-go/events/README_CloudWatch_Logs.md
  22. 15
      vendor/github.com/aws/aws-lambda-go/events/README_CodeBuild.md
  23. 17
      vendor/github.com/aws/aws-lambda-go/events/README_CodeCommit.md
  24. 15
      vendor/github.com/aws/aws-lambda-go/events/README_CodeDeploy.md
  25. 32
      vendor/github.com/aws/aws-lambda-go/events/README_Cognito.md
  26. 69
      vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_CustomAuthLambdaTriggers.md
  27. 25
      vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PostConfirmation.md
  28. 25
      vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreAuthentication.md
  29. 27
      vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreSignup.md
  30. 26
      vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreTokenGen.md
  31. 18
      vendor/github.com/aws/aws-lambda-go/events/README_Config.md
  32. 35
      vendor/github.com/aws/aws-lambda-go/events/README_Connect.md
  33. 80
      vendor/github.com/aws/aws-lambda-go/events/README_DynamoDB.md
  34. 33
      vendor/github.com/aws/aws-lambda-go/events/README_Kinesis.md
  35. 45
      vendor/github.com/aws/aws-lambda-go/events/README_KinesisDataAnalytics.md
  36. 45
      vendor/github.com/aws/aws-lambda-go/events/README_KinesisFirehose.md
  37. 31
      vendor/github.com/aws/aws-lambda-go/events/README_Lex.md
  38. 30
      vendor/github.com/aws/aws-lambda-go/events/README_S3.md
  39. 39
      vendor/github.com/aws/aws-lambda-go/events/README_S3_Batch_Job.md
  40. 30
      vendor/github.com/aws/aws-lambda-go/events/README_SES.md
  41. 21
      vendor/github.com/aws/aws-lambda-go/events/README_SNS.md
  42. 29
      vendor/github.com/aws/aws-lambda-go/events/README_SQS.md
  43. 34
      vendor/github.com/aws/aws-lambda-go/events/alb.go
  44. 242
      vendor/github.com/aws/aws-lambda-go/events/apigw.go
  45. 40
      vendor/github.com/aws/aws-lambda-go/events/appsync.go
  46. 542
      vendor/github.com/aws/aws-lambda-go/events/attributevalue.go
  47. 18
      vendor/github.com/aws/aws-lambda-go/events/autoscaling.go
  48. 31
      vendor/github.com/aws/aws-lambda-go/events/chime_bot.go
  49. 20
      vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events.go
  50. 55
      vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs.go
  51. 101
      vendor/github.com/aws/aws-lambda-go/events/code_commit.go
  52. 197
      vendor/github.com/aws/aws-lambda-go/events/codebuild.go
  53. 80
      vendor/github.com/aws/aws-lambda-go/events/codedeploy.go
  54. 74
      vendor/github.com/aws/aws-lambda-go/events/codepipeline_job.go
  55. 266
      vendor/github.com/aws/aws-lambda-go/events/cognito.go
  56. 17
      vendor/github.com/aws/aws-lambda-go/events/config.go
  57. 50
      vendor/github.com/aws/aws-lambda-go/events/connect.go
  58. 45
      vendor/github.com/aws/aws-lambda-go/events/duration.go
  59. 134
      vendor/github.com/aws/aws-lambda-go/events/dynamodb.go
  60. 59
      vendor/github.com/aws/aws-lambda-go/events/epoch_time.go
  61. 44
      vendor/github.com/aws/aws-lambda-go/events/firehose.go
  62. 9
      vendor/github.com/aws/aws-lambda-go/events/iot_button.go
  63. 27
      vendor/github.com/aws/aws-lambda-go/events/kinesis.go
  64. 28
      vendor/github.com/aws/aws-lambda-go/events/kinesis_analytics.go
  65. 71
      vendor/github.com/aws/aws-lambda-go/events/lex.go
  66. 64
      vendor/github.com/aws/aws-lambda-go/events/s3.go
  67. 39
      vendor/github.com/aws/aws-lambda-go/events/s3_batch_job.go
  68. 95
      vendor/github.com/aws/aws-lambda-go/events/ses.go
  69. 32
      vendor/github.com/aws/aws-lambda-go/events/sns.go
  70. 28
      vendor/github.com/aws/aws-lambda-go/events/sqs.go
  71. 3
      vendor/github.com/aws/aws-lambda-go/lambda/README.md
  72. 62
      vendor/github.com/aws/aws-lambda-go/lambda/entry.go
  73. 97
      vendor/github.com/aws/aws-lambda-go/lambda/function.go
  74. 144
      vendor/github.com/aws/aws-lambda-go/lambda/handler.go
  75. 44
      vendor/github.com/aws/aws-lambda-go/lambda/handlertrace/trace.go
  76. 3
      vendor/github.com/aws/aws-lambda-go/lambda/messages/README.md
  77. 43
      vendor/github.com/aws/aws-lambda-go/lambda/messages/messages.go
  78. 99
      vendor/github.com/aws/aws-lambda-go/lambda/panic.go
  79. 3
      vendor/github.com/aws/aws-lambda-go/lambdacontext/README.md
  80. 89
      vendor/github.com/aws/aws-lambda-go/lambdacontext/context.go
  81. 7
      vendor/modules.txt

3
.gitignore vendored

@ -23,4 +23,5 @@ dlv
rootfs/
dist
coverage.txt
.DS_Store
.DS_Store
.aws-sam

@ -1,3 +1,7 @@
## Unreleased (Master)
* [2282](https://github.com/grafana/loki/pull/2282) **owen-d**: introduces a [lambda-promtail](https://github.com/grafana/loki/blob/master/docs/clients/lambda-promtail/README.md) workflow for shipping Cloudwatch logs to Loki.
## 1.5.0 (2020-05-20)
It's been a busy month and a half since 1.4.0 was released, and a lot of new improvements have been added to Loki since!

@ -11,6 +11,7 @@ Loki supports the following official clients for sending logs:
- [Fluentd](fluentd/)
- [Fluent Bit](fluentbit/)
- [Logstash](logstash/)
- [Lambda Promtail](/lambda-promtail/)
## Picking a client
@ -51,6 +52,12 @@ Prometheus plugin.
If you are already using logstash and/or beats, this will be the easiest way to start.
By adding our output plugin you can quickly try Loki without doing big configuration changes.
### Lambda Promtail
This is a workflow combining the promtail push-api [scrape config](./promtail/configuration#loki_push_api_config) and the [lambda-promtail](../../tools/lambda-promtail/) AWS Lambda function which pipes logs from Cloudwatch to Loki.
This is a good choice if you're looking to try out Loki in a low-footprint way or if you wish to monitor AWS lambda logs in Loki.
# Unofficial clients
Please note that the Loki API is not stable yet, so breaking changes might occur

@ -0,0 +1,84 @@
# Lambda Promtail
Loki includes an [AWS SAM](https://aws.amazon.com/serverless/sam/) package template for shipping Cloudwatch logs to Loki via a set of promtails [here](../../../tools/lambda-promtail/). This is done via an intermediary [lambda function](https://aws.amazon.com/lambda/) which processes cloudwatch events and propagates them to a promtail instance (or set of instances behind a load balancer) via the push-api [scrape config](docs/clients/promtail/configuration#loki_push_api_config).
## Uses
### Ephemeral Jobs
This workflow is intended to be an effective approach for monitoring ephemeral jobs such as those run on AWS Lambda which are otherwise hard/impossible to monitor via one of the other Loki [clients](../).
Ephemeral jobs can quite easily run afoul of cardinality best practices. During high request load, an AWS lambda function might balloon in concurrency, creating many log streams in Cloudwatch. However, these may only be active for a very short while. This creates a problem for combining these short-lived log streams in Loki because timestamps may not strictly increase across multiple log streams. The other obvious route is creating labels based on log streams, which is also undesirable because it leads to cardinality problems via many low-throughput log streams.
Instead we can pipeline Cloudwatch logs to a set of promtails, which can mitigate these problem in two ways:
1) Using promtail's push api along with the `use_incoming_timestamp: false` config, we let promtail determine the timestamp based on when it ingests the logs, not the timestamp assigned by cloudwatch. Obviously, this means that we lose the origin timestamp because promtail now assigns it, but this is a relatively small difference in a real time ingestion system like this.
2) In conjunction with (1), promtail can coalesce logs across Cloudwatch log streams because it's no longer susceptible to `out-of-order` errors when combining multiple sources (lambda invocations).
One important aspect to keep in mind when running with a set of promtails behind a load balancer is that we're effectively moving the cardinality problems from the `number_of_log_streams` -> `number_of_promtails`. You'll need to assign a promtail specific label on each promtail so that you don't run into `out-of-order` errors when the promtails send data for the same log groups to Loki. This can easily be done via a config like `--client.external-labels=promtail=${HOSTNAME}` passed to promtail.
### Proof of concept Loki deployments
For those using Cloudwatch and wishing to test out Loki in a low-risk way, this workflow allows piping Cloudwatch logs to Loki regardless of the event source (EC2, Kubernetes, Lambda, ECS, etc) without setting up a set of promtail daemons across their infrastructure. However, running promtail as a daemon on your infrastructure is the best-practice deployment strategy in the long term for flexibility, reliability, performance, and cost.
Note: Propagating logs from Cloudwatch to Loki means you'll still need to _pay_ for Cloudwatch.
## Propagated Labels
Incoming logs will have three special labels assigned to them which can be used in [relabeling](../promtail#relabel_config) or later stages in a promtail [pipeline](../promtail/pipelines):
- `__aws_cloudwatch_log_group`: The associated Cloudwatch Log Group for this log.
- `__aws_cloudwatch_log_stream`: The associated Cloudwatch Log Stream for this log.
- `__aws_cloudwatch_owner`: The AWS ID of the owner of this event.
## Limitations
### Promtail labels
As stated earlier, this workflow moves the worst case stream cardinality from `number_of_log_streams` -> `number_of_log_groups` * `number_of_promtails`. For this reason, each promtail must have a unique label attached to logs it processes (ideally via something like `--client.external-labels=promtail=${HOSTNAME}`) and it's advised to run a small number of promtails behind a load balancer according to your throughput and redundancy needs.
This trade-off is very effective when you have a large number of log streams but want to aggregate them by the log group. This is very common in AWS Lambda, where log groups are the "application" and log streams are the individual application containers which are spun up and down at a whim, possibly just for a single function invocation.
### Data Persistence
#### Availability
For availability concerns, run a set of promtails behind a load balancer.
#### Batching
Since promtail batches writes to Loki for performance, it's possible that promtail will receive a log, issue a successful `204` http status code for the write, then be killed at a later time before it writes upstream to Loki. This should be rare, but is a downside this workflow has.
### Templating
The current SAM template is rudimentary. If you need to add vpc configs, extra log groups to monitor, subnet declarations, etc, you'll need to edit the template manually. Currently this requires pulling the Loki source.
## Example Promtail Config
Note: this should be run in conjunction with a promtail-specific label attached, ideally via a flag argument like `--client.external-labels=promtail=${HOSTNAME}`. It will receive writes via the push-api on ports `3500` (http) and `3600` (grpc).
```yaml
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://ip_or_hostname_where_Loki_run:3100/loki/api/v1/push
scrape_configs:
- job_name: push1
loki_push_api:
server:
http_listen_port: 3500
grpc_listen_port: 3600
labels:
# Adds a label on all streams indicating it was processed by the lambda-promtail workflow.
promtail: 'lambda-promtail'
relabel_configs:
# Maps the cloudwatch log group into a label called `log_group` for use in Loki.
- source_labels: ['__aws_cloudwatch_log_group']
target_label: 'log_group'
```

@ -3,6 +3,7 @@ module github.com/grafana/loki
go 1.14
require (
github.com/aws/aws-lambda-go v1.17.0
github.com/blang/semver v3.5.1+incompatible // indirect
github.com/bmatcuk/doublestar v1.2.2
github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee

@ -163,7 +163,10 @@ github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY=
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496 h1:zV3ejI06GQ59hwDQAvmK1qxOQGB3WuVTRoY0okPTAv0=
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg=
github.com/aws/aws-lambda-go v1.13.3 h1:SuCy7H3NLyp+1Mrfp+m80jcbi9KYWAs9/BXwppwRDzY=
github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU=
github.com/aws/aws-lambda-go v1.17.0 h1:Ogihmi8BnpmCNktKAGpNwSiILNNING1MiosnKUfU8m0=
github.com/aws/aws-lambda-go v1.17.0/go.mod h1:FEwgPLE6+8wcGBTe5cJN3JWurd1Ztm9zN4jsXsjzKKw=
github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM=
github.com/aws/aws-sdk-go v1.17.7/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/aws/aws-sdk-go v1.22.4/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
@ -1227,6 +1230,7 @@ github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
github.com/vektah/gqlparser v1.1.2/go.mod h1:1ycwN7Ij5njmMkPPAOaRFY4rET2Enx7IkVv3vaXspKw=
github.com/weaveworks/common v0.0.0-20200206153930-760e36ae819a/go.mod h1:6enWAqfQBFrE8X/XdJwZr8IKgh1chStuFR0mjU/UOUw=
github.com/weaveworks/common v0.0.0-20200625145055-4b1847531bc9 h1:dNVIG9aKQHR9T4uYAC4YxmkHHryOsfTwsL54WrS7u28=

@ -0,0 +1,15 @@
UNAME_S := $(shell uname -s)
LOCAL_PORT ?= 8080
ifeq ($(UNAME_S),Linux)
LOCAL_ENDPOINT=http://localhost:$(LOCAL_PORT)/loki/api/v1/push
else
LOCAL_ENDPOINT=http://host.docker.internal:$(LOCAL_PORT)/loki/api/v1/push
endif
.PHONY: build
build:
sam build
dry-run:
echo $$(sam local generate-event cloudwatch logs) | sam local invoke LambdaPromtailFunction -e - --parameter-overrides PromtailAddress=$(LOCAL_ENDPOINT)

@ -0,0 +1,120 @@
# lambda-promtail
This is a sample template for lambda-promtail - Below is a brief explanation of what we have generated for you:
```bash
.
├── Makefile <-- Make to automate build
├── README.md <-- This instructions file
├── hello-world <-- Source code for a lambda function
│ └── main.go <-- Lambda function code
└── template.yaml
```
## Requirements
* AWS CLI already configured with Administrator permission
* [Docker installed](https://www.docker.com/community-edition)
* [Golang](https://golang.org)
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
## Setup process
### Installing dependencies & building the target
In this example we use the built-in `sam build` to automatically download all the dependencies and package our build target.
Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html)
The `sam build` command is wrapped inside of the `Makefile`. To execute this simply run
```shell
make
```
### Local development
**Invoking function locally
```bash
make dry-run
```
## Packaging and deployment
AWS Lambda Golang runtime requires a flat folder with the executable generated on build step. SAM will use `CodeUri` property to know where to look up for the application:
```bash
make build
```
To deploy your application for the first time, first make sure you've set the following parameters in the template:
- `LogGroup`
- `PromtailAddress`
- `ReservedConcurrency`
These can also be set via overrides by passing the following argument to `sam deploy`:
```
--parameter-overrides Optional. A string that contains AWS
CloudFormation parameter overrides encoded
as key=value pairs.For example, 'ParameterKe
y=KeyPairName,ParameterValue=MyKey Parameter
Key=InstanceType,ParameterValue=t1.micro' or
KeyPairName=MyKey InstanceType=t1.micro
```
Also, if your deployment requires a VPC configuration, make sure to edit the `VpcConfig` field in the `template.yaml` manually.
Then run the following in your shell:
```bash
sam deploy --guided --capabilities CAPABILITY_IAM,CAPABILITY_NAMED_IAM --parameter-overrides PromtailAddress=<>,LogGroup=<>
```
The command will package and deploy your application to AWS, with a series of prompts:
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
* **AWS Region**: The AWS region you want to deploy your app to.
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modified IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
# Appendix
### Golang installation
Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install
A quickstart way would be to use Homebrew, chocolatey or your linux package manager.
#### Homebrew (Mac)
Issue the following command from the terminal:
```shell
brew install golang
```
If it's already installed, run the following command to ensure it's the latest version:
```shell
brew update
brew upgrade golang
```
#### Chocolatey (Windows)
Issue the following command from the powershell:
```shell
choco install golang
```
If it's already installed, run the following command to ensure it's the latest version:
```shell
choco upgrade golang
```
## Limitations
- Error handling: If promtail is unresponsive, `lambda-promtail` will drop logs after `retry_count`, which defaults to 2.
- AWS does not support passing log lines over 256kb to lambdas.

@ -0,0 +1,102 @@
package main
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/cortexproject/cortex/pkg/util"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/grafana/loki/pkg/logproto"
"github.com/prometheus/common/model"
)
const (
// We use snappy-encoded protobufs over http by default.
contentType = "application/x-protobuf"
maxErrMsgLen = 1024
)
var promtailAddress *url.URL
func init() {
addr := os.Getenv("PROMTAIL_ADDRESS")
if addr == "" {
panic(errors.New("required environmental variable PROMTAIL_ADDRESS not present"))
}
var err error
promtailAddress, err = url.Parse(addr)
if err != nil {
panic(err)
}
}
func handler(ctx context.Context, ev events.CloudwatchLogsEvent) error {
data, err := ev.AWSLogs.Parse()
if err != nil {
return err
}
stream := logproto.Stream{
Labels: model.LabelSet{
model.LabelName("__aws_cloudwatch_log_group"): model.LabelValue(data.LogGroup),
model.LabelName("__aws_cloudwatch_log_stream"): model.LabelValue(data.LogStream),
model.LabelName("__aws_cloudwatch_owner"): model.LabelValue(data.Owner),
}.String(),
Entries: make([]logproto.Entry, 0, len(data.LogEvents)),
}
for _, entry := range data.LogEvents {
stream.Entries = append(stream.Entries, logproto.Entry{
Line: entry.Message,
// It's best practice to ignore timestamps from cloudwatch as promtail is responsible for adding those.
Timestamp: util.TimeFromMillis(entry.Timestamp),
})
}
buf, err := proto.Marshal(&logproto.PushRequest{
Streams: []logproto.Stream{stream},
})
if err != nil {
return err
}
// Push to promtail
buf = snappy.Encode(nil, buf)
req, err := http.NewRequest("POST", promtailAddress.String(), bytes.NewReader(buf))
if err != nil {
return err
}
req.Header.Set("Content-Type", contentType)
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return err
}
if resp.StatusCode/100 != 2 {
scanner := bufio.NewScanner(io.LimitReader(resp.Body, maxErrMsgLen))
line := ""
if scanner.Scan() {
line = scanner.Text()
}
err = fmt.Errorf("server returned HTTP status %s (%d): %s", resp.Status, resp.StatusCode, line)
}
return err
}
func main() {
lambda.Start(handler)
}

@ -0,0 +1,61 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
lambda-promtail:
propagate Cloudwatch Logs to Loki via Promtail.
Parameters:
LogGroup:
Description: 'Required. The Log Group to forward to Promtail.'
Type: String
PromtailAddress:
Description: 'address for promtail in the form of: http<s>://<location><:port>/loki/api/v1/push'
Type: String
Default: 'http://localhost:8080/loki/api/v1/push'
ReservedConcurrency:
Description: The maximum of concurrent executions you want to reserve for the function.
Type: Number
Default: 2
Resources:
LambdaPromtailFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: lambda-promtail/
Handler: handler
MemorySize: 128
Timeout: 60
EventInvokeConfig:
MaximumRetryAttempts: 2
Policies:
- Statement:
Effect: Allow
Action:
- 'logs:DescribeLogGroups'
- 'logs:DescribeLogStreams'
- 'logs:FilterLogEvents'
- 'logs:GetLogEvents'
Resource: '*'
ReservedConcurrentExecutions: !Ref ReservedConcurrency
# # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html
# VpcConfig:
Runtime: go1.x
Events:
CatchAll:
Type: CloudWatchLogs
Properties:
LogGroupName: !Ref LogGroup
FilterPattern: ''
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
PROMTAIL_ADDRESS: !Ref PromtailAddress
Outputs:
LambdaPromtailFunction:
Description: "Lambda Promtail Function ARN"
Value: !GetAtt LambdaPromtailFunction.Arn
LambdaPromtailFunctionIamRole:
Description: "Implicit IAM Role created for LambdaPromtail function"
Value: !GetAtt LambdaPromtailFunctionRole.Arn

@ -0,0 +1,203 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -0,0 +1,15 @@
MIT No Attribution
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,7 @@
Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Lambda functions are made available under a modified MIT license.
See LICENSE-LAMBDACODE for details.
The remainder of the project is made available under the terms of the
Apache License, version 2.0. See LICENSE for details.

@ -0,0 +1,49 @@
# Overview
[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/events?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/events)
This package provides input types for Lambda functions that process AWS events.
# Samples
[API Gateway](README_ApiGatewayEvent.md)
[API Gateway Custom Authorizer](README_ApiGatewayCustomAuthorizer.md)
[AppSync](README_AppSync.md)
[CloudFormation Events](../cfn/README.md)
[CloudWatch Events](README_CloudWatch_Events.md)
[CloudWatch Logs](README_CloudWatch_Logs.md)
[Chime Bot Events](README_Chime_Bots.md)
[Code Commit Events](README_CodeCommit.md)
[Cognito Events](README_Cognito.md)
[Cognito PostConfirmation](README_Cognito_UserPools_PostConfirmation.md)
[Cognito PreSignup](README_Cognito_UserPools_PreSignup.md)
[Cognito PreTokenGen](README_Cognito_UserPools_PreTokenGen.md)
[Config Events](README_Config.md)
[DynamoDB Events](README_DynamoDB.md)
[Kinesis Events](README_Kinesis.md)
[Kinesis Firehose Events](README_KinesisFirehose.md)
[Lex Events](README_Lex.md)
[S3 Events](README_S3.md)
[SES Events](README_SES.md)
[SNS Events](README_SNS.md)
[SQS Events](README_SQS.md)

@ -0,0 +1,38 @@
# Overview
ALB Target Group events consist of a request that was routed to a Lambda function which is a registered target of an Application Load Balancer Target Group. When this happens, ALB expects the result of the function to be the response that ALB should respond with.
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
# Sample Function
The following is a sample class and Lambda function that receives an ALB Target Group event as an input, writes some of the incoming data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handleRequest(ctx context.Context, request events.ALBTargetGroupRequest) (events.ALBTargetGroupResponse, error) {
fmt.Printf("Processing request data for traceId %s.\n", request.Headers["x-amzn-trace-id"])
fmt.Printf("Body size = %d.\n", len(request.Body))
fmt.Println("Headers:")
for key, value := range request.Headers {
fmt.Printf(" %s: %s\n", key, value)
}
return events.ALBTargetGroupResponse{Body: request.Body, StatusCode: 200, StatusDescription: "200 OK", IsBase64Encoded: false, Headers: map[string]string{}}, nil
}
func main() {
lambda.Start(handleRequest)
}
```

@ -0,0 +1,67 @@
# Sample Function
The following is a simple TOKEN authorizer example to demonstrate how to use an authorization
token to allow or deny a request. In this example, the caller named "user" is allowed to invoke
a request if the client-supplied token value is "allow". The caller is not allowed to invoke
the request if the token value is "deny". If the token value is "Unauthorized", the function
returns the "Unauthorized" error with an HTTP status code of 401. For any other token value,
the authorizer returns an "Invalid token" error.
This example is based on the [JavaScript sample](https://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-token-lambda-function-create) from the API Gateway documentation
```go
package main
import (
"context"
"errors"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// Help function to generate an IAM policy
func generatePolicy(principalId, effect, resource string) events.APIGatewayCustomAuthorizerResponse {
authResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}
if effect != "" && resource != "" {
authResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{
Version: "2012-10-17",
Statement: []events.IAMPolicyStatement{
{
Action: []string{"execute-api:Invoke"},
Effect: effect,
Resource: []string{resource},
},
},
}
}
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.Context = map[string]interface{}{
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true,
}
return authResponse
}
func handleRequest(ctx context.Context, event events.APIGatewayCustomAuthorizerRequest) (events.APIGatewayCustomAuthorizerResponse, error) {
token := event.AuthorizationToken
switch strings.ToLower(token) {
case "allow":
return generatePolicy("user", "Allow", event.MethodArn), nil
case "deny":
return generatePolicy("user", "Deny", event.MethodArn), nil
case "unauthorized":
return events.APIGatewayCustomAuthorizerResponse{}, errors.New("Unauthorized") // Return a 401 Unauthorized response
default:
return events.APIGatewayCustomAuthorizerResponse{}, errors.New("Error: Invalid token")
}
}
func main() {
lambda.Start(handleRequest)
}
```

@ -0,0 +1,36 @@
# Overview
API Gateway events consist of a request that was routed to a Lambda function by API Gateway. When this happens, API Gateway expects the result of the function to be the response that API Gateway should respond with.
# Sample Function
The following is a sample class and Lambda function that receives Amazon API Gateway event record data as an input, writes some of the record data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fmt.Printf("Processing request data for request %s.\n", request.RequestContext.RequestID)
fmt.Printf("Body size = %d.\n", len(request.Body))
fmt.Println("Headers:")
for key, value := range request.Headers {
fmt.Printf(" %s: %s\n", key, value)
}
return events.APIGatewayProxyResponse{Body: request.Body, StatusCode: 200}, nil
}
func main() {
lambda.Start(handleRequest)
}
```

@ -0,0 +1,21 @@
# Sample Function
The following is a sample Lambda function that receives an Auto Scaling event as an input and logs the EC2 instance ID to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handler(ctx context.Context, autoScalingEvent events.AutoScalingEvent) {
fmt.Printf("Instance-Id available in event is %s \n", autoScalingEvent.Detail["EC2InstanceId"])
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,67 @@
# Sample Function
The following is a sample class and Lambda function that receives a Amazon Chime Bot event and handles the various event types accordingly.
```go
package main
import (
"fmt"
"context"
"net/http"
"bytes"
"encoding/json"
"errors"
"strconv"
"github.com/aws/aws-lambda-go/events"
)
func handler(_ context.Context, chimeBotEvent events.ChimeBotEvent) error {
switch chimeBotEvent.EventType {
case "Invite":
if err := message(chimeBotEvent.InboundHTTPSEndpoint.URL, "Thanks for inviting me to this room " + chimeBotEvent.Sender.SenderID); err != nil {
return fmt.Errorf("failed to send webhook message: %v", err)
}
return nil
case "Mention":
if err := message(chimeBotEvent.InboundHTTPSEndpoint.URL, "Thanks for mentioning me " + chimeBotEvent.Sender.SenderID); err != nil {
return fmt.Errorf("failed to send webhook message: %v", err)
}
return nil
case "Remove":
fmt.Printf("I have been removed from %q by %q", chimeBotEvent.Discussion.DiscussionType, chimeBotEvent.Sender.SenderID)
return nil
default:
return fmt.Errorf("event type %q is unsupported", chimeBotEvent.EventType)
}
}
func message(url, content string) (error) {
input := &bytes.Buffer{}
if err := json.NewEncoder(input).Encode(webhookInput{Content:content}); err != nil {
return errors.New("failed to marshal request: " + err.Error())
}
resp, err := http.Post("POST", url, input)
if err != nil {
return errors.New("failed to execute post http request: " + err.Error())
}
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if resp.StatusCode != http.StatusOK {
return errors.New("bad response: status code not is " + strconv.Itoa(http.StatusOK) + " not " + strconv.Itoa(resp.StatusCode))
}
return nil
}
type webhookInput struct {
Content string `json:"Content"`
}
```

@ -0,0 +1,17 @@
# Sample Function
The following is a Lambda function that receives Amazon CloudWatch event record data as input and writes event detail to Lambda's CloudWatch Logs. Note that by default anything written to Console will be logged as CloudWatch Logs events.
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handler(ctx context.Context, event events.CloudWatchEvent) {
fmt.Printf("Detail = %s\n", event.Detail)
}
```

@ -0,0 +1,20 @@
# Sample Function
The following is a Lambda function that receives Amazon CloudWatch Logs event record data as input and writes message part to Lambda's CloudWatch Logs. Note that by default anything written to Console will be logged as CloudWatch Logs events.
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handler(ctx context.Context, logsEvent events.CloudwatchLogsEvent) {
data, _ := logsEvent.AWSLogs.Parse()
for _, logEvent := range data.LogEvents {
fmt.Printf("Message = %s\n", logEvent.Message)
}
}
```

@ -0,0 +1,15 @@
# Sample Function
The following is a sample Lambda function that receives an Amazon CodeBuild event
and writes it to standard output.
```go
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handleRequest(evt events.CodeBuildEvent) {
fmt.Println(evt)
}
```

@ -0,0 +1,17 @@
# Sample Function
The following is a sample Lambda function that receives Amazon CodeCommit event
records input and prints them to `os.Stdout`.)
```go
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handleRequest(evt events.CodeCommitEvent) {
for _, record := range evt.Records {
fmt.Println(record)
}
}
```

@ -0,0 +1,15 @@
# Sample Function
The following is a sample Lambda function that receives an Amazon CodeDeploy event
and writes it to standard output.
```go
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handleRequest(evt events.CodeDeployEvent) {
fmt.Println(evt)
}
```

@ -0,0 +1,32 @@
# Sample Function
The following is a sample Lambda function that receives Amazon Cognito Sync event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(cognitoEvent events.CognitoEvent) error {
for datasetName, datasetRecord := range cognitoEvent.DatasetRecords {
fmt.Printf("[%s -- %s] %s -> %s -> %s \n",
cognitoEvent.EventType,
datasetName,
datasetRecord.OldValue,
datasetRecord.Op,
datasetRecord.NewValue)
}
return nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,69 @@
# Sample Function
The following is a sample Lambda functions that are used for custom authentication with Cognito User Pools.
These Lambda triggers issue and verify their own challenges as part of a user pool [custom authentication flow](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-custom-authentication-flow).
Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html
Define Auth Challenge Lambda Trigger:
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(event *events.CognitoEventUserPoolsDefineAuthChallenge) (*events.CognitoEventUserPoolsDefineAuthChallenge, error) {
fmt.Printf("Define Auth Challenge: %+v\n", event)
return event, nil
}
func main() {
lambda.Start(handler)
}
```
Create Auth Challenge Lambda Trigger:
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(event *events.CognitoEventUserPoolsCreateAuthChallenge) (*events.CognitoEventUserPoolsCreateAuthChallenge, error) {
fmt.Printf("Create Auth Challenge: %+v\n", event)
return event, nil
}
func main() {
lambda.Start(handler)
}
```
Verify Auth Challenge Response Lambda Trigger:
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(event *events.CognitoEventUserPoolsVerifyAuthChallenge) (*events.CognitoEventUserPoolsVerifyAuthChallenge, error) {
fmt.Printf("Verify Auth Challenge: %+v\n", event)
return event, nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,25 @@
# Sample Function
The following is a sample Lambda function that receives Amazon Cognito User Pools post-confirmation event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html .
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(event events.CognitoEventUserPoolsPostConfirmation) (events.CognitoEventUserPoolsPostConfirmation, error) {
fmt.Printf("PostConfirmation for user: %s\n", event.UserName)
return event, nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,25 @@
# Sample Function
The following is a sample Lambda function that receives Amazon Cognito User Pools pre-authentication event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html .
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(event events.CognitoEventUserPoolsPreAuthentication) (events.CognitoEventUserPoolsPreAuthentication, error) {
fmt.Printf("PreAuthentication of user: %s\n", event.UserName)
return event, nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,27 @@
# Sample Function
The following is a sample Lambda function that receives Amazon Cognito User Pools pre-signup event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html .
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// handler is the lambda handler invoked by the `lambda.Start` function call
func handler(event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) {
fmt.Printf("PreSignup of user: %s\n", event.UserName)
event.Response.AutoConfirmUser = true
return event, nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,26 @@
# Sample Function
The following is a sample Lambda function that receives Amazon Cognito User Pools pre-token-gen event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html .
```go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(event events.CognitoEventUserPoolsPreTokenGen) (events.CognitoEventUserPoolsPreTokenGen, error) {
fmt.Printf("PreTokenGen of user: %s\n", event.UserName)
event.Response.ClaimsOverrideDetails.ClaimsToSuppress = []string{"family_name"}
return event, nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,18 @@
# Sample Function
The following is a sample Lambda function that receives Amazon Config event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
import (
"strings"
"github.com/aws/aws-lambda-go/events"
)
func handleRequest(ctx context.Context, configEvent events.ConfigEvent) {
fmt.Printf("AWS Config rule: %s\n", configEvent.ConfigRuleName)
fmt.Printf("Invoking event JSON: %s\n", configEvent.InvokingEvent)
fmt.Printf("Event version: %s\n", configEvent.Version)
}
```

@ -0,0 +1,35 @@
# Sample Function
The following is a sample Lambda function that receives an Amazon Connect event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func main() {
lambda.Start(handler)
}
func handler(ctx context.Context, connectEvent events.ConnectEvent) (events.ConnectResponse, error) {
fmt.Printf("Processing Connect event with ContactID %s.\n", connectEvent.Details.ContactData.ContactID)
fmt.Printf("Invoked with %d parameters\n", len(connectEvent.Details.Parameters))
for k, v := range connectEvent.Details.Parameters {
fmt.Printf("%s : %s\n", k, v)
}
resp := events.ConnectResponse{
"Result": "Success",
"NewAttribute": "NewValue",
}
return resp, nil
}
```

@ -0,0 +1,80 @@
# Sample Function
The following is a sample Lambda function that receives DynamoDB event data as input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs.)
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handleRequest(ctx context.Context, e events.DynamoDBEvent) {
for _, record := range e.Records {
fmt.Printf("Processing request data for event ID %s, type %s.\n", record.EventID, record.EventName)
// Print new values for attributes of type String
for name, value := range record.Change.NewImage {
if value.DataType() == events.DataTypeString {
fmt.Printf("Attribute name: %s, value: %s\n", name, value.String())
}
}
}
}
```
# Reading attribute values
Stream notifications are delivered to the Lambda handler whenever data in the DynamoDB table is modified.
Depending on the Stream settings, a StreamRecord may contain the following data:
* Keys: key attributes of the modified item.
* NewImage: the entire item, as it appears after it was modified.
* OldImage: the entire item, as it appeared before it was modified.
The values for the attributes can be accessed using the AttributeValue type. For each type
supported natively by DynamoDB, there is a corresponding accessor method:
DynamoDB type | AttributeValue accessor method | Return type | DataType constant
---------------|--------------------------------|---------------------------|------------------
B (Binary) | Binary() | []byte | DataTypeBinary
BOOL (Boolean) | Boolean() | bool | DataTypeBoolean
BS (Binary Set)| BinarySet() | [][]byte | DataTypeBinarySet
L (List) | List() | []AttributeValue | DataTypeList
M (Map) | Map() | map[string]AttributeValue | DataTypeMap
N (Number) | Number() / Integer() / Float() | string / int64 / float64 | DataTypeNumber
NS (Number Set)| NumberSet() | []string | DataTypeNumberSet
NULL (Null) | IsNull() | bool | DataTypeNull
S (String) | String() | string | DataTypeString
SS (String Set)| StringSet() | []string | DataTypeStringSet
Calling the accessor method for the incorrect type will result in a panic. If the type needs to
be discovered in runtime, the method DataType() can be used in order to determine the correct accessor.
More information about DynamoDB data types can be seen [in this documentation](http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html).
The following example reads values of attributes name and age, for which types are known to be String and Number:
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handleRequest(ctx context.Context, e events.DynamoDBEvent) {
for _, record := range e.Records {
fmt.Printf("Processing request data for event ID %s, type %s.\n", record.EventID, record.EventName)
// Print new values for attributes name and age
name := record.Change.NewImage["name"].String()
age, _ := record.Change.NewImage["age"].Integer()
fmt.Printf("Name: %s, age: %d\n", name, age)
}
}
```

@ -0,0 +1,33 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon Kinesis event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handler(ctx context.Context, kinesisEvent events.KinesisEvent) error {
for _, record := range kinesisEvent.Records {
kinesisRecord := record.Kinesis
dataBytes := kinesisRecord.Data
dataText := string(dataBytes)
fmt.Printf("%s Data = %s \n", record.EventName, dataText)
}
return nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,45 @@
# Sample function
The following is an example for an Application Destination Lambda function that receives Amazon Kinesis Data Analytics event records as an input. To send Kinesis Data Analytics output records the Lamdbda function must be compliant with the (required input and return data models)[https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-output-lambda.html], so the handler returns a list of delivery statuses for each record.
The following Lambda function receives Amazon Kinesis Data Analytics event record data as an input and writes some of the record data to CloudWatch Logs. For each entry it adds an element to the response slice, marking it delivered. When the logic considers the delivery to be failed the `events.KinesisAnalyticsOutputDeliveryFailed` value should be used for the response `Result` field.
```go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handler(ctx context.Context, kinesisAnalyticsEvent events.KinesisAnalyticsOutputDeliveryEvent) (events.KinesisAnalyticsOutputDeliveryResponse, error) {
var err error
var responses events.KinesisAnalyticsOutputDeliveryResponse
responses.Records = make([]events.KinesisAnalyticsOutputDeliveryResponseRecord, len(kinesisAnalyticsEvent.Records))
for i, record := range kinesisAnalyticsEvent.Records {
responses.Records[i] = events.KinesisAnalyticsOutputDeliveryResponseRecord{
RecordID: record.RecordID,
Result: events.KinesisAnalyticsOutputDeliveryOK,
}
dataBytes := record.Data
dataText := string(dataBytes)
fmt.Printf("%s Data = %s \n", record.RecordID, dataText)
}
return responses, err
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,45 @@
# Sample Function
The following is a sample Lambda function that transforms Kinesis Firehose records by doing a ToUpper on the data.
```go
package main
import (
"fmt"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handleRequest(evnt events.KinesisFirehoseEvent) (events.KinesisFirehoseResponse, error) {
fmt.Printf("InvocationID: %s\n", evnt.InvocationID)
fmt.Printf("DeliveryStreamArn: %s\n", evnt.DeliveryStreamArn)
fmt.Printf("Region: %s\n", evnt.Region)
var response events.KinesisFirehoseResponse
for _, record := range evnt.Records {
fmt.Printf("RecordID: %s\n", record.RecordID)
fmt.Printf("ApproximateArrivalTimestamp: %s\n", record.ApproximateArrivalTimestamp)
// Transform data: ToUpper the data
var transformedRecord events.KinesisFirehoseResponseRecord
transformedRecord.RecordID = record.RecordID
transformedRecord.Result = events.KinesisFirehoseTransformedStateOk
transformedRecord.Data = []byte(strings.ToUpper(string(record.Data)))
response.Records = append(response.Records, transformedRecord)
}
return response, nil
}
func main() {
lambda.Start(handleRequest)
}
```

@ -0,0 +1,31 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon Lex event data as input, writes some of the record data to CloudWatch Logs, and responds back to Lex. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func Handler(ctx context.Context, event events.LexEvent) (*lex.LexResponse, error) {
fmt.Printf("Received an input from Amazon Lex. Current Intent: %s", event.CurrentIntent.Name)
messageContent := "Hello from AWS Lambda!"
return &LexResponse{
SessionAttributes: event.SessionAttributes,
DialogAction: events.LexDialogAction{
Type: "Close",
Message: map[string]string{
"content": messageContent,
"contentType": "PlainText",
},
FulfillmentState: "Fulfilled",
},
}, nil
}
```

@ -0,0 +1,30 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon S3 event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
// main.go
package main
import (
"fmt"
"context"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func handler(ctx context.Context, s3Event events.S3Event) {
for _, record := range s3Event.Records {
s3 := record.S3
fmt.Printf("[%s - %s] Bucket = %s, Key = %s \n", record.EventSource, record.EventTime, s3.Bucket.Name, s3.Object.Key)
}
}
func main() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(handler)
}
```

@ -0,0 +1,39 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon S3 event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
import (
"fmt"
"context"
"github.com/aws/aws-lambda-go/events"
)
func handler(ctx context.Context, e events.S3BatchJobEvent) (response events.S3BatchJobResponse, err error) {
fmt.Printf("InvocationSchemaVersion: %s\n", e.InvocationSchemaVersion)
fmt.Printf("InvocationID: %s\n", e.InvocationID)
fmt.Printf("Job.ID: %s\n", e.Job.ID)
for _, task := range e.Tasks {
fmt.Printf("TaskID: %s\n", task.TaskID)
fmt.Printf("S3Key: %s\n", task.S3Key)
fmt.Printf("S3VersionID: %s\n", task.S3VersionID)
fmt.Printf("S3BucketARN: %s\n", task.S3BucketARN)
}
fmt.Printf("InvocationSchemaVersion: %s\n", response.InvocationSchemaVersion)
fmt.Printf("TreatMissingKeysAs: %s\n", response.TreatMissingKeysAs)
fmt.Printf("InvocationID: %s\n", response.InvocationID)
for _, result := range response.Results {
fmt.Printf("TaskID: %s\n", result.TaskID)
fmt.Printf("ResultCode: %s\n", result.ResultCode)
fmt.Printf("ResultString: %s\n", result.ResultString)
}
return
}
```

@ -0,0 +1,30 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon SES event message data as input, writes some of the message data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handler(ctx context.Context, sesEvent events.SimpleEmailEvent) error {
for _, record := range sesEvent.Records {
ses := record.SES
fmt.Printf("[%s - %s] Mail = %+v, Receipt = %+v \n", record.EventVersion, record.EventSource, ses.Mail, ses.Receipt)
}
return nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,21 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon SNS event record data as input, writes some of the record data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
)
func handler(ctx context.Context, snsEvent events.SNSEvent) {
for _, record := range snsEvent.Records {
snsRecord := record.SNS
fmt.Printf("[%s %s] Message = %s \n", record.EventSource, snsRecord.Timestamp, snsRecord.Message)
}
}
```

@ -0,0 +1,29 @@
# Sample Function
The following is a sample class and Lambda function that receives Amazon SQS event message data as input, writes some of the message data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)
```go
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handler(ctx context.Context, sqsEvent events.SQSEvent) error {
for _, message := range sqsEvent.Records {
fmt.Printf("The message %s for event source %s = %s \n", message.MessageId, message.EventSource, message.Body)
}
return nil
}
func main() {
lambda.Start(handler)
}
```

@ -0,0 +1,34 @@
package events
// ALBTargetGroupRequest contains data originating from the ALB Lambda target group integration
type ALBTargetGroupRequest struct {
HTTPMethod string `json:"httpMethod"`
Path string `json:"path"`
QueryStringParameters map[string]string `json:"queryStringParameters,omitempty"`
MultiValueQueryStringParameters map[string][]string `json:"multiValueQueryStringParameters,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders,omitempty"`
RequestContext ALBTargetGroupRequestContext `json:"requestContext"`
IsBase64Encoded bool `json:"isBase64Encoded"`
Body string `json:"body"`
}
// ALBTargetGroupRequestContext contains the information to identify the load balancer invoking the lambda
type ALBTargetGroupRequestContext struct {
ELB ELBContext `json:"elb"`
}
// ELBContext contains the information to identify the ARN invoking the lambda
type ELBContext struct {
TargetGroupArn string `json:"targetGroupArn"`
}
// ALBTargetGroupResponse configures the response to be returned by the ALB Lambda target group for the request
type ALBTargetGroupResponse struct {
StatusCode int `json:"statusCode"`
StatusDescription string `json:"statusDescription"`
Headers map[string]string `json:"headers"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded"`
}

@ -0,0 +1,242 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// APIGatewayProxyRequest contains data coming from the API Gateway proxy
type APIGatewayProxyRequest struct {
Resource string `json:"resource"` // The resource path defined in API Gateway
Path string `json:"path"` // The url path for the caller
HTTPMethod string `json:"httpMethod"`
Headers map[string]string `json:"headers"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
QueryStringParameters map[string]string `json:"queryStringParameters"`
MultiValueQueryStringParameters map[string][]string `json:"multiValueQueryStringParameters"`
PathParameters map[string]string `json:"pathParameters"`
StageVariables map[string]string `json:"stageVariables"`
RequestContext APIGatewayProxyRequestContext `json:"requestContext"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"`
}
// APIGatewayProxyResponse configures the response to be returned by API Gateway for the request
type APIGatewayProxyResponse struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"`
}
// APIGatewayProxyRequestContext contains the information to identify the AWS account and resources invoking the
// Lambda function. It also includes Cognito identity information for the caller.
type APIGatewayProxyRequestContext struct {
AccountID string `json:"accountId"`
ResourceID string `json:"resourceId"`
OperationName string `json:"operationName,omitempty"`
Stage string `json:"stage"`
DomainName string `json:"domainName"`
DomainPrefix string `json:"domainPrefix"`
RequestID string `json:"requestId"`
Protocol string `json:"protocol"`
Identity APIGatewayRequestIdentity `json:"identity"`
ResourcePath string `json:"resourcePath"`
Authorizer map[string]interface{} `json:"authorizer"`
HTTPMethod string `json:"httpMethod"`
RequestTime string `json:"requestTime"`
RequestTimeEpoch int64 `json:"requestTimeEpoch"`
APIID string `json:"apiId"` // The API Gateway rest API Id
}
// APIGatewayV2HTTPRequest contains data coming from the new HTTP API Gateway
type APIGatewayV2HTTPRequest struct {
Version string `json:"version"`
RouteKey string `json:"routeKey"`
RawPath string `json:"rawPath"`
RawQueryString string `json:"rawQueryString"`
Cookies []string `json:"cookies,omitempty"`
Headers map[string]string `json:"headers"`
QueryStringParameters map[string]string `json:"queryStringParameters,omitempty"`
PathParameters map[string]string `json:"pathParameters,omitempty"`
RequestContext APIGatewayV2HTTPRequestContext `json:"requestContext"`
StageVariables map[string]string `json:"stageVariables,omitempty"`
Body string `json:"body,omitempty"`
IsBase64Encoded bool `json:"isBase64Encoded"`
}
// APIGatewayV2HTTPRequestContext contains the information to identify the AWS account and resources invoking the Lambda function.
type APIGatewayV2HTTPRequestContext struct {
RouteKey string `json:"routeKey"`
AccountID string `json:"accountId"`
Stage string `json:"stage"`
RequestID string `json:"requestId"`
Authorizer *APIGatewayV2HTTPRequestContextAuthorizerDescription `json:"authorizer,omitempty"`
APIID string `json:"apiId"` // The API Gateway HTTP API Id
DomainName string `json:"domainName"`
DomainPrefix string `json:"domainPrefix"`
Time string `json:"time"`
TimeEpoch int64 `json:"timeEpoch"`
HTTP APIGatewayV2HTTPRequestContextHTTPDescription `json:"http"`
}
// APIGatewayV2HTTPRequestContextAuthorizerDescription contains authorizer information for the request context.
type APIGatewayV2HTTPRequestContextAuthorizerDescription struct {
JWT APIGatewayV2HTTPRequestContextAuthorizerJWTDescription `json:"jwt"`
}
// APIGatewayV2HTTPRequestContextAuthorizerJWTDescription contains JWT authorizer information for the request context.
type APIGatewayV2HTTPRequestContextAuthorizerJWTDescription struct {
Claims map[string]string `json:"claims"`
Scopes []string `json:"scopes"`
}
// APIGatewayV2HTTPRequestContextHTTPDescription contains HTTP information for the request context.
type APIGatewayV2HTTPRequestContextHTTPDescription struct {
Method string `json:"method"`
Path string `json:"path"`
Protocol string `json:"protocol"`
SourceIP string `json:"sourceIp"`
UserAgent string `json:"userAgent"`
}
// APIGatewayV2HTTPResponse configures the response to be returned by API Gateway V2 for the request
type APIGatewayV2HTTPResponse struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"`
Cookies []string `json:"cookies"`
}
// APIGatewayRequestIdentity contains identity information for the request caller.
type APIGatewayRequestIdentity struct {
CognitoIdentityPoolID string `json:"cognitoIdentityPoolId"`
AccountID string `json:"accountId"`
CognitoIdentityID string `json:"cognitoIdentityId"`
Caller string `json:"caller"`
APIKey string `json:"apiKey"`
APIKeyID string `json:"apiKeyId"`
AccessKey string `json:"accessKey"`
SourceIP string `json:"sourceIp"`
CognitoAuthenticationType string `json:"cognitoAuthenticationType"`
CognitoAuthenticationProvider string `json:"cognitoAuthenticationProvider"`
UserArn string `json:"userArn"`
UserAgent string `json:"userAgent"`
User string `json:"user"`
}
// APIGatewayWebsocketProxyRequest contains data coming from the API Gateway proxy
type APIGatewayWebsocketProxyRequest struct {
Resource string `json:"resource"` // The resource path defined in API Gateway
Path string `json:"path"` // The url path for the caller
HTTPMethod string `json:"httpMethod"`
Headers map[string]string `json:"headers"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
QueryStringParameters map[string]string `json:"queryStringParameters"`
MultiValueQueryStringParameters map[string][]string `json:"multiValueQueryStringParameters"`
PathParameters map[string]string `json:"pathParameters"`
StageVariables map[string]string `json:"stageVariables"`
RequestContext APIGatewayWebsocketProxyRequestContext `json:"requestContext"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"`
}
// APIGatewayWebsocketProxyRequestContext contains the information to identify
// the AWS account and resources invoking the Lambda function. It also includes
// Cognito identity information for the caller.
type APIGatewayWebsocketProxyRequestContext struct {
AccountID string `json:"accountId"`
ResourceID string `json:"resourceId"`
Stage string `json:"stage"`
RequestID string `json:"requestId"`
Identity APIGatewayRequestIdentity `json:"identity"`
ResourcePath string `json:"resourcePath"`
Authorizer interface{} `json:"authorizer"`
HTTPMethod string `json:"httpMethod"`
APIID string `json:"apiId"` // The API Gateway rest API Id
ConnectedAt int64 `json:"connectedAt"`
ConnectionID string `json:"connectionId"`
DomainName string `json:"domainName"`
Error string `json:"error"`
EventType string `json:"eventType"`
ExtendedRequestID string `json:"extendedRequestId"`
IntegrationLatency string `json:"integrationLatency"`
MessageDirection string `json:"messageDirection"`
MessageID interface{} `json:"messageId"`
RequestTime string `json:"requestTime"`
RequestTimeEpoch int64 `json:"requestTimeEpoch"`
RouteKey string `json:"routeKey"`
Status string `json:"status"`
}
// APIGatewayCustomAuthorizerRequestTypeRequestIdentity contains identity information for the request caller.
type APIGatewayCustomAuthorizerRequestTypeRequestIdentity struct {
APIKey string `json:"apiKey"`
SourceIP string `json:"sourceIp"`
}
// APIGatewayCustomAuthorizerContext represents the expected format of an API Gateway custom authorizer response.
// Deprecated. Code should be updated to use the Authorizer map from APIGatewayRequestIdentity. Ex: Authorizer["principalId"]
type APIGatewayCustomAuthorizerContext struct {
PrincipalID *string `json:"principalId"`
StringKey *string `json:"stringKey,omitempty"`
NumKey *int `json:"numKey,omitempty"`
BoolKey *bool `json:"boolKey,omitempty"`
}
// APIGatewayCustomAuthorizerRequestTypeRequestContext represents the expected format of an API Gateway custom authorizer response.
type APIGatewayCustomAuthorizerRequestTypeRequestContext struct {
Path string `json:"path"`
AccountID string `json:"accountId"`
ResourceID string `json:"resourceId"`
Stage string `json:"stage"`
RequestID string `json:"requestId"`
Identity APIGatewayCustomAuthorizerRequestTypeRequestIdentity `json:"identity"`
ResourcePath string `json:"resourcePath"`
HTTPMethod string `json:"httpMethod"`
APIID string `json:"apiId"`
}
// APIGatewayCustomAuthorizerRequest contains data coming in to a custom API Gateway authorizer function.
type APIGatewayCustomAuthorizerRequest struct {
Type string `json:"type"`
AuthorizationToken string `json:"authorizationToken"`
MethodArn string `json:"methodArn"`
}
// APIGatewayCustomAuthorizerRequestTypeRequest contains data coming in to a custom API Gateway authorizer function.
type APIGatewayCustomAuthorizerRequestTypeRequest struct {
Type string `json:"type"`
MethodArn string `json:"methodArn"`
Resource string `json:"resource"`
Path string `json:"path"`
HTTPMethod string `json:"httpMethod"`
Headers map[string]string `json:"headers"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
QueryStringParameters map[string]string `json:"queryStringParameters"`
MultiValueQueryStringParameters map[string][]string `json:"multiValueQueryStringParameters"`
PathParameters map[string]string `json:"pathParameters"`
StageVariables map[string]string `json:"stageVariables"`
RequestContext APIGatewayCustomAuthorizerRequestTypeRequestContext `json:"requestContext"`
}
// APIGatewayCustomAuthorizerResponse represents the expected format of an API Gateway authorization response.
type APIGatewayCustomAuthorizerResponse struct {
PrincipalID string `json:"principalId"`
PolicyDocument APIGatewayCustomAuthorizerPolicy `json:"policyDocument"`
Context map[string]interface{} `json:"context,omitempty"`
UsageIdentifierKey string `json:"usageIdentifierKey,omitempty"`
}
// APIGatewayCustomAuthorizerPolicy represents an IAM policy
type APIGatewayCustomAuthorizerPolicy struct {
Version string
Statement []IAMPolicyStatement
}
// IAMPolicyStatement represents one statement from IAM policy with action, effect and resource
type IAMPolicyStatement struct {
Action []string
Effect string
Resource []string
}

@ -0,0 +1,40 @@
package events
import "encoding/json"
// AppSyncResolverTemplate represents the requests from AppSync to Lambda
type AppSyncResolverTemplate struct {
Version string `json:"version"`
Operation AppSyncOperation `json:"operation"`
Payload json.RawMessage `json:"payload"`
}
// AppSyncIAMIdentity contains information about the caller authed via IAM.
type AppSyncIAMIdentity struct {
AccountID string `json:"accountId"`
CognitoIdentityPoolID string `json:"cognitoIdentityPoolId"`
CognitoIdentityID string `json:"cognitoIdentityId"`
SourceIP []string `json:"sourceIp"`
Username string `json:"username"`
UserARN string `json:"userArn"`
}
// AppSyncCognitoIdentity contains information about the caller authed via Cognito.
type AppSyncCognitoIdentity struct {
Sub string `json:"sub"`
Issuer string `json:"issuer"`
Username string `json:"username"`
Claims map[string]interface{} `json:"claims"`
SourceIP []string `json:"sourceIp"`
DefaultAuthStrategy string `json:"defaultAuthStrategy"`
}
// AppSyncOperation specifies the operation type supported by Lambda operations
type AppSyncOperation string
const (
// OperationInvoke lets AWS AppSync know to call your Lambda function for every GraphQL field resolver
OperationInvoke AppSyncOperation = "Invoke"
// OperationBatchInvoke instructs AWS AppSync to batch requests for the current GraphQL field
OperationBatchInvoke AppSyncOperation = "BatchInvoke"
)

@ -0,0 +1,542 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strconv"
)
// DynamoDBAttributeValue provides convenient access for a value stored in DynamoDB.
// For more information, please see http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html
type DynamoDBAttributeValue struct {
value anyValue
dataType DynamoDBDataType
}
// This struct represents DynamoDBAttributeValue which doesn't
// implement fmt.Stringer interface and safely `fmt.Sprintf`able
type dynamoDbAttributeValue DynamoDBAttributeValue
// Binary provides access to an attribute of type Binary.
// Method panics if the attribute is not of type Binary.
func (av DynamoDBAttributeValue) Binary() []byte {
av.ensureType(DataTypeBinary)
return av.value.([]byte)
}
// Boolean provides access to an attribute of type Boolean.
// Method panics if the attribute is not of type Boolean.
func (av DynamoDBAttributeValue) Boolean() bool {
av.ensureType(DataTypeBoolean)
return av.value.(bool)
}
// BinarySet provides access to an attribute of type Binary Set.
// Method panics if the attribute is not of type BinarySet.
func (av DynamoDBAttributeValue) BinarySet() [][]byte {
av.ensureType(DataTypeBinarySet)
return av.value.([][]byte)
}
// List provides access to an attribute of type List. Each element
// of the list is an DynamoDBAttributeValue itself.
// Method panics if the attribute is not of type List.
func (av DynamoDBAttributeValue) List() []DynamoDBAttributeValue {
av.ensureType(DataTypeList)
return av.value.([]DynamoDBAttributeValue)
}
// Map provides access to an attribute of type Map. They Keys are strings
// and the values are DynamoDBAttributeValue instances.
// Method panics if the attribute is not of type Map.
func (av DynamoDBAttributeValue) Map() map[string]DynamoDBAttributeValue {
av.ensureType(DataTypeMap)
return av.value.(map[string]DynamoDBAttributeValue)
}
// Number provides access to an attribute of type Number.
// DynamoDB sends the values as strings. For convenience please see also
// the methods Integer() and Float().
// Method panics if the attribute is not of type Number.
func (av DynamoDBAttributeValue) Number() string {
av.ensureType(DataTypeNumber)
return av.value.(string)
}
// Integer provides access to an attribute of type Number.
// DynamoDB sends the values as strings. For convenience this method
// provides conversion to int. If the value cannot be represented by
// a signed integer, err.Err = ErrRange and the returned value is the maximum magnitude integer
// of an int64 of the appropriate sign.
// Method panics if the attribute is not of type Number.
func (av DynamoDBAttributeValue) Integer() (int64, error) {
number := av.Number()
value, err := strconv.ParseInt(number, 10, 64)
if err == nil {
return value, nil
}
s, err := strconv.ParseFloat(number, 64)
return int64(s), err
}
// Float provides access to an attribute of type Number.
// DynamoDB sends the values as strings. For convenience this method
// provides conversion to float64.
// The returned value is the nearest floating point number rounded using IEEE754 unbiased rounding.
// If the number is more than 1/2 ULP away from the largest floating point number of the given size,
// the value returned is ±Inf, err.Err = ErrRange.
// Method panics if the attribute is not of type Number.
func (av DynamoDBAttributeValue) Float() (float64, error) {
s, err := strconv.ParseFloat(av.Number(), 64)
return s, err
}
// NumberSet provides access to an attribute of type Number Set.
// DynamoDB sends the numbers as strings.
// Method panics if the attribute is not of type Number.
func (av DynamoDBAttributeValue) NumberSet() []string {
av.ensureType(DataTypeNumberSet)
return av.value.([]string)
}
// String provides access to an attribute of type String.
// Method panics if the attribute is not of type String.
func (av DynamoDBAttributeValue) String() string {
if av.dataType == DataTypeString {
return av.value.(string)
}
// If dataType is not DataTypeString during fmt.Sprintf("%#v", ...)
// compiler confuses with fmt.Stringer interface and panics
// instead of printing the struct.
return fmt.Sprintf("%v", dynamoDbAttributeValue(av))
}
// StringSet provides access to an attribute of type String Set.
// Method panics if the attribute is not of type String Set.
func (av DynamoDBAttributeValue) StringSet() []string {
av.ensureType(DataTypeStringSet)
return av.value.([]string)
}
// IsNull returns true if the attribute is of type Null.
func (av DynamoDBAttributeValue) IsNull() bool {
return av.value == nil
}
// DataType provides access to the DynamoDB type of the attribute
func (av DynamoDBAttributeValue) DataType() DynamoDBDataType {
return av.dataType
}
// NewBinaryAttribute creates an DynamoDBAttributeValue containing a Binary
func NewBinaryAttribute(value []byte) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeBinary
return av
}
// NewBooleanAttribute creates an DynamoDBAttributeValue containing a Boolean
func NewBooleanAttribute(value bool) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeBoolean
return av
}
// NewBinarySetAttribute creates an DynamoDBAttributeValue containing a BinarySet
func NewBinarySetAttribute(value [][]byte) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeBinarySet
return av
}
// NewListAttribute creates an DynamoDBAttributeValue containing a List
func NewListAttribute(value []DynamoDBAttributeValue) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeList
return av
}
// NewMapAttribute creates an DynamoDBAttributeValue containing a Map
func NewMapAttribute(value map[string]DynamoDBAttributeValue) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeMap
return av
}
// NewNumberAttribute creates an DynamoDBAttributeValue containing a Number
func NewNumberAttribute(value string) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeNumber
return av
}
// NewNumberSetAttribute creates an DynamoDBAttributeValue containing a NumberSet
func NewNumberSetAttribute(value []string) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeNumberSet
return av
}
// NewNullAttribute creates an DynamoDBAttributeValue containing a Null
func NewNullAttribute() DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.dataType = DataTypeNull
return av
}
// NewStringAttribute creates an DynamoDBAttributeValue containing a String
func NewStringAttribute(value string) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeString
return av
}
// NewStringSetAttribute creates an DynamoDBAttributeValue containing a StringSet
func NewStringSetAttribute(value []string) DynamoDBAttributeValue {
var av DynamoDBAttributeValue
av.value = value
av.dataType = DataTypeStringSet
return av
}
// DynamoDBDataType specifies the type supported natively by DynamoDB for an attribute
type DynamoDBDataType int
const (
DataTypeBinary DynamoDBDataType = iota
DataTypeBoolean
DataTypeBinarySet
DataTypeList
DataTypeMap
DataTypeNumber
DataTypeNumberSet
DataTypeNull
DataTypeString
DataTypeStringSet
)
type anyValue interface{}
// UnsupportedDynamoDBTypeError is the error returned when trying to unmarshal a DynamoDB Attribute type not recognized by this library
type UnsupportedDynamoDBTypeError struct {
Type string
}
func (e UnsupportedDynamoDBTypeError) Error() string {
return fmt.Sprintf("unsupported DynamoDB attribute type, %v", e.Type)
}
// IncompatibleDynamoDBTypeError is the error passed in a panic when calling an accessor for an incompatible type
type IncompatibleDynamoDBTypeError struct {
Requested DynamoDBDataType
Actual DynamoDBDataType
}
func (e IncompatibleDynamoDBTypeError) Error() string {
return fmt.Sprintf("accessor called for incompatible type, requested type %v but actual type was %v", e.Requested, e.Actual)
}
func (av *DynamoDBAttributeValue) ensureType(expectedType DynamoDBDataType) {
if av.dataType != expectedType {
panic(IncompatibleDynamoDBTypeError{Requested: expectedType, Actual: av.dataType})
}
}
// MarshalJSON implements custom marshaling to be used by the standard json/encoding package
func (av DynamoDBAttributeValue) MarshalJSON() ([]byte, error) {
var buff bytes.Buffer
var err error
var b []byte
switch av.dataType {
case DataTypeBinary:
buff.WriteString(`{ "B":`)
b, err = json.Marshal(av.value.([]byte))
buff.Write(b)
case DataTypeBoolean:
buff.WriteString(`{ "BOOL":`)
b, err = json.Marshal(av.value.(bool))
buff.Write(b)
case DataTypeBinarySet:
buff.WriteString(`{ "BS":`)
b, err = json.Marshal(av.value.([][]byte))
buff.Write(b)
case DataTypeList:
buff.WriteString(`{ "L":`)
b, err = json.Marshal(av.value.([]DynamoDBAttributeValue))
buff.Write(b)
case DataTypeMap:
buff.WriteString(`{ "M":`)
b, err = json.Marshal(av.value.(map[string]DynamoDBAttributeValue))
buff.Write(b)
case DataTypeNumber:
buff.WriteString(`{ "N":`)
b, err = json.Marshal(av.value.(string))
buff.Write(b)
case DataTypeNumberSet:
buff.WriteString(`{ "NS":`)
b, err = json.Marshal(av.value.([]string))
buff.Write(b)
case DataTypeNull:
buff.WriteString(`{ "NULL": true `)
case DataTypeString:
buff.WriteString(`{ "S":`)
b, err = json.Marshal(av.value.(string))
buff.Write(b)
case DataTypeStringSet:
buff.WriteString(`{ "SS":`)
b, err = json.Marshal(av.value.([]string))
buff.Write(b)
}
buff.WriteString(`}`)
return buff.Bytes(), err
}
func unmarshalNull(target *DynamoDBAttributeValue) error {
target.value = nil
target.dataType = DataTypeNull
return nil
}
func unmarshalString(target *DynamoDBAttributeValue, value interface{}) error {
var ok bool
target.value, ok = value.(string)
target.dataType = DataTypeString
if !ok {
return errors.New("DynamoDBAttributeValue: S type should contain a string")
}
return nil
}
func unmarshalBinary(target *DynamoDBAttributeValue, value interface{}) error {
stringValue, ok := value.(string)
if !ok {
return errors.New("DynamoDBAttributeValue: B type should contain a base64 string")
}
binaryValue, err := base64.StdEncoding.DecodeString(stringValue)
if err != nil {
return err
}
target.value = binaryValue
target.dataType = DataTypeBinary
return nil
}
func unmarshalBoolean(target *DynamoDBAttributeValue, value interface{}) error {
booleanValue, ok := value.(bool)
if !ok {
return errors.New("DynamoDBAttributeValue: BOOL type should contain a boolean")
}
target.value = booleanValue
target.dataType = DataTypeBoolean
return nil
}
func unmarshalBinarySet(target *DynamoDBAttributeValue, value interface{}) error {
list, ok := value.([]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: BS type should contain a list of base64 strings")
}
binarySet := make([][]byte, len(list))
for index, element := range list {
var err error
elementString := element.(string)
binarySet[index], err = base64.StdEncoding.DecodeString(elementString)
if err != nil {
return err
}
}
target.value = binarySet
target.dataType = DataTypeBinarySet
return nil
}
func unmarshalList(target *DynamoDBAttributeValue, value interface{}) error {
list, ok := value.([]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: L type should contain a list")
}
DynamoDBAttributeValues := make([]DynamoDBAttributeValue, len(list))
for index, element := range list {
elementMap, ok := element.(map[string]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: element of a list is not an DynamoDBAttributeValue")
}
var elementDynamoDBAttributeValue DynamoDBAttributeValue
err := unmarshalDynamoDBAttributeValueMap(&elementDynamoDBAttributeValue, elementMap)
if err != nil {
return errors.New("DynamoDBAttributeValue: unmarshal of child DynamoDBAttributeValue failed")
}
DynamoDBAttributeValues[index] = elementDynamoDBAttributeValue
}
target.value = DynamoDBAttributeValues
target.dataType = DataTypeList
return nil
}
func unmarshalMap(target *DynamoDBAttributeValue, value interface{}) error {
m, ok := value.(map[string]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: M type should contain a map")
}
DynamoDBAttributeValues := make(map[string]DynamoDBAttributeValue)
for k, v := range m {
elementMap, ok := v.(map[string]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: element of a map is not an DynamoDBAttributeValue")
}
var elementDynamoDBAttributeValue DynamoDBAttributeValue
err := unmarshalDynamoDBAttributeValueMap(&elementDynamoDBAttributeValue, elementMap)
if err != nil {
return errors.New("DynamoDBAttributeValue: unmarshal of child DynamoDBAttributeValue failed")
}
DynamoDBAttributeValues[k] = elementDynamoDBAttributeValue
}
target.value = DynamoDBAttributeValues
target.dataType = DataTypeMap
return nil
}
func unmarshalNumber(target *DynamoDBAttributeValue, value interface{}) error {
var ok bool
target.value, ok = value.(string)
target.dataType = DataTypeNumber
if !ok {
return errors.New("DynamoDBAttributeValue: N type should contain a string")
}
return nil
}
func unmarshalNumberSet(target *DynamoDBAttributeValue, value interface{}) error {
list, ok := value.([]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: NS type should contain a list of strings")
}
numberSet := make([]string, len(list))
for index, element := range list {
numberSet[index], ok = element.(string)
if !ok {
return errors.New("DynamoDBAttributeValue: NS type should contain a list of strings")
}
}
target.value = numberSet
target.dataType = DataTypeNumberSet
return nil
}
func unmarshalStringSet(target *DynamoDBAttributeValue, value interface{}) error {
list, ok := value.([]interface{})
if !ok {
return errors.New("DynamoDBAttributeValue: SS type should contain a list of strings")
}
stringSet := make([]string, len(list))
for index, element := range list {
stringSet[index], ok = element.(string)
if !ok {
return errors.New("DynamoDBAttributeValue: SS type should contain a list of strings")
}
}
target.value = stringSet
target.dataType = DataTypeStringSet
return nil
}
func unmarshalDynamoDBAttributeValue(target *DynamoDBAttributeValue, typeLabel string, jsonValue interface{}) error {
switch typeLabel {
case "NULL":
return unmarshalNull(target)
case "B":
return unmarshalBinary(target, jsonValue)
case "BOOL":
return unmarshalBoolean(target, jsonValue)
case "BS":
return unmarshalBinarySet(target, jsonValue)
case "L":
return unmarshalList(target, jsonValue)
case "M":
return unmarshalMap(target, jsonValue)
case "N":
return unmarshalNumber(target, jsonValue)
case "NS":
return unmarshalNumberSet(target, jsonValue)
case "S":
return unmarshalString(target, jsonValue)
case "SS":
return unmarshalStringSet(target, jsonValue)
default:
target.value = nil
target.dataType = DataTypeNull
return UnsupportedDynamoDBTypeError{typeLabel}
}
}
// UnmarshalJSON unmarshals a JSON description of this DynamoDBAttributeValue
func (av *DynamoDBAttributeValue) UnmarshalJSON(b []byte) error {
var m map[string]interface{}
err := json.Unmarshal(b, &m)
if err != nil {
return err
}
return unmarshalDynamoDBAttributeValueMap(av, m)
}
func unmarshalDynamoDBAttributeValueMap(target *DynamoDBAttributeValue, m map[string]interface{}) error {
if m == nil {
return errors.New("DynamoDBAttributeValue: does not contain a map")
}
if len(m) != 1 {
return errors.New("DynamoDBAttributeValue: map must contain a single type")
}
for k, v := range m {
return unmarshalDynamoDBAttributeValue(target, k, v)
}
return nil
}

@ -0,0 +1,18 @@
package events
import (
"time"
)
// AutoScalingEvent struct is used to parse the json for auto scaling event types //
type AutoScalingEvent struct {
Version string `json:"version"` // The version of event data
ID string `json:"id"` // The unique ID of the event
DetailType string `json:"detail-type"` //Details about event type
Source string `json:"source"` //Source of the event
AccountID string `json:"account"` //AccountId
Time time.Time `json:"time"` //Event timestamp
Region string `json:"region"` //Region of event
Resources []string `json:"resources"` //Information about resources impacted by event
Detail map[string]interface{} `json:"detail"`
}

@ -0,0 +1,31 @@
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"time"
)
type ChimeBotEvent struct {
Sender ChimeBotEventSender `json:"Sender"`
Discussion ChimeBotEventDiscussion `json:"Discussion"`
EventType string `json:"EventType"`
InboundHTTPSEndpoint *ChimeBotEventInboundHTTPSEndpoint `json:"InboundHttpsEndpoint,omitempty"`
EventTimestamp time.Time `json:"EventTimestamp"`
Message string `json:"Message,omitempty"`
}
type ChimeBotEventSender struct {
SenderID string `json:"SenderId"`
SenderIDType string `json:"SenderIdType"`
}
type ChimeBotEventDiscussion struct {
DiscussionID string `json:"DiscussionId"`
DiscussionType string `json:"DiscussionType"`
}
type ChimeBotEventInboundHTTPSEndpoint struct {
EndpointType string `json:"EndpointType"`
URL string `json:"Url"`
}

@ -0,0 +1,20 @@
package events
import (
"encoding/json"
"time"
)
// CloudWatchEvent is the outer structure of an event sent via CloudWatch Events.
// For examples of events that come via CloudWatch Events, see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html
type CloudWatchEvent struct {
Version string `json:"version"`
ID string `json:"id"`
DetailType string `json:"detail-type"`
Source string `json:"source"`
AccountID string `json:"account"`
Time time.Time `json:"time"`
Region string `json:"region"`
Resources []string `json:"resources"`
Detail json.RawMessage `json:"detail"`
}

@ -0,0 +1,55 @@
package events
import (
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
)
// CloudwatchLogsEvent represents raw data from a cloudwatch logs event
type CloudwatchLogsEvent struct {
AWSLogs CloudwatchLogsRawData `json:"awslogs"`
}
// CloudwatchLogsRawData contains gzipped base64 json representing the bulk
// of a cloudwatch logs event
type CloudwatchLogsRawData struct {
Data string `json:"data"`
}
// Parse returns a struct representing a usable CloudwatchLogs event
func (c CloudwatchLogsRawData) Parse() (d CloudwatchLogsData, err error) {
data, err := base64.StdEncoding.DecodeString(c.Data)
if err != nil {
return
}
zr, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return
}
defer zr.Close()
dec := json.NewDecoder(zr)
err = dec.Decode(&d)
return
}
// CloudwatchLogsData is an unmarshal'd, ungzip'd, cloudwatch logs event
type CloudwatchLogsData struct {
Owner string `json:"owner"`
LogGroup string `json:"logGroup"`
LogStream string `json:"logStream"`
SubscriptionFilters []string `json:"subscriptionFilters"`
MessageType string `json:"messageType"`
LogEvents []CloudwatchLogsLogEvent `json:"logEvents"`
}
// CloudwatchLogsLogEvent represents a log entry from cloudwatch logs
type CloudwatchLogsLogEvent struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
Message string `json:"message"`
}

@ -0,0 +1,101 @@
package events
import (
"errors"
"fmt"
"time"
)
// CodeCommitEvent represents a CodeCommit event
type CodeCommitEvent struct {
Records []CodeCommitRecord `json:"Records"`
}
// String returns a string representation of this object.
// Useful for testing and debugging.
func (e CodeCommitEvent) String() string {
return fmt.Sprintf("{Records: %v}", e.Records)
}
type CodeCommitEventTime time.Time
// https://golang.org/pkg/time/#Parse
const codeCommitEventTimeReference = "\"2006-01-2T15:04:05.000-0700\""
func (t *CodeCommitEventTime) MarshalJSON() ([]byte, error) {
if t == nil {
return nil, errors.New("CodeCommitEventTime cannot be nil")
}
gt := time.Time(*t)
return []byte(gt.Format(codeCommitEventTimeReference)), nil
}
func (t *CodeCommitEventTime) UnmarshalJSON(data []byte) error {
if t == nil {
return errors.New("CodeCommitEventTime cannot be nil")
}
pt, err := time.Parse(codeCommitEventTimeReference, string(data))
if err == nil {
*t = CodeCommitEventTime(pt)
}
return err
}
// CodeCommitRecord represents a CodeCommit record
type CodeCommitRecord struct {
EventID string `json:"eventId"`
EventVersion string `json:"eventVersion"`
EventTime CodeCommitEventTime `json:"eventTime"`
EventTriggerName string `json:"eventTriggerName"`
EventPartNumber uint64 `json:"eventPartNumber"`
CodeCommit CodeCommitCodeCommit `json:"codecommit"`
EventName string `json:"eventName"`
EventTriggerConfigId string `json:"eventTriggerConfigId"`
EventSourceARN string `json:"eventSourceARN"`
UserIdentityARN string `json:"userIdentityARN"`
EventSource string `json:"eventSource"`
AWSRegion string `json:"awsRegion"`
EventTotalParts uint64 `json:"eventTotalParts"`
CustomData string `json:"customData,omitempty"`
}
// String returns a string representation of this object.
// Useful for testing and debugging.
func (r CodeCommitRecord) String() string {
return fmt.Sprintf(
"{eventId: %v, eventVersion: %v, eventTime: %v, eventTriggerName: %v, "+
"eventPartNumber: %v, codeCommit: %v, eventName: %v, "+
"eventTriggerConfigId: %v, eventSourceARN: %v, userIdentityARN: %v, "+
"eventSource: %v, awsRegion: %v, eventTotalParts: %v, customData: %v}",
r.EventID, r.EventVersion, r.EventTime, r.EventTriggerName,
r.EventPartNumber, r.CodeCommit, r.EventName,
r.EventTriggerConfigId, r.EventSourceARN, r.UserIdentityARN,
r.EventSource, r.AWSRegion, r.EventTotalParts, r.CustomData)
}
// CodeCommitCodeCommit represents a CodeCommit object in a record
type CodeCommitCodeCommit struct {
References []CodeCommitReference `json:"references"`
}
// String returns a string representation of this object.
// Useful for testing and debugging.
func (c CodeCommitCodeCommit) String() string {
return fmt.Sprintf("{references: %v}", c.References)
}
// CodeCommitReference represents a Reference object in a CodeCommit object
type CodeCommitReference struct {
Commit string `json:"commit"`
Ref string `json:"ref"`
Created bool `json:"created,omitempty"`
}
// String returns a string representation of this object.
// Useful for testing and debugging.
func (r CodeCommitReference) String() string {
return fmt.Sprintf(
"{commit: %v, ref: %v, created: %v}", r.Commit, r.Ref, r.Created)
}

@ -0,0 +1,197 @@
package events
import (
"encoding/json"
"time"
)
const (
CodeBuildEventSource = "aws.codebuild"
CodeBuildStateChangeDetailType = "CodeBuild Build State Change"
CodeBuildPhaseChangeDetailType = "CodeBuild Build Phase Change"
)
// CodeBuildPhaseStatus represents the status of code build phase (i.e. failed, in progress)
type CodeBuildPhaseStatus string
const (
CodeBuildPhaseStatusFailed CodeBuildPhaseStatus = "FAILED"
CodeBuildPhaseStatusFault = "FAULT"
CodeBuildPhaseStatusInProgress = "IN_PROGRESS"
CodeBuildPhaseStatusQueued = "QUEUED"
CodeBuildPhaseStatusStopped = "STOPPED"
CodeBuildPhaseStatusSucceeded = "SUCCEEDED"
CodeBuildPhaseStatusTimedOut = "TIMED_OUT"
)
// CodeBuildPhaseType represents the type of the code build phase (i.e. submitted, install)
type CodeBuildPhaseType string
const (
CodeBuildPhaseTypeSubmitted CodeBuildPhaseType = "SUBMITTED"
CodeBuildPhaseTypeQueued = "QUEUED"
CodeBuildPhaseTypeProvisioning = "PROVISIONING"
CodeBuildPhaseTypeDownloadSource = "DOWNLOAD_SOURCE"
CodeBuildPhaseTypeInstall = "INSTALL"
CodeBuildPhaseTypePreBuild = "PRE_BUILD"
CodeBuildPhaseTypeBuild = "BUILD"
CodeBuildPhaseTypePostBuild = "POST_BUILD"
CodeBuildPhaseTypeUploadArtifacts = "UPLOAD_ARTIFACTS"
CodeBuildPhaseTypeFinalizing = "FINALIZING"
CodeBuildPhaseTypeCompleted = "COMPLETED"
)
// CodeBuildEvent is documented at:
// https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html#sample-build-notifications-ref
type CodeBuildEvent struct {
// AccountID is the id of the AWS account from which the event originated.
AccountID string `json:"account"`
// Region is the AWS region from which the event originated.
Region string `json:"region"`
// DetailType informs the schema of the Detail field. For build state-change
// events, the value will be CodeBuildStateChangeDetailType. For phase-change
// events, it will be CodeBuildPhaseChangeDetailType.
DetailType string `json:"detail-type"`
// Source should be equal to CodeBuildEventSource.
Source string `json:"source"`
// Version is the version of the event's schema.
Version string `json:"version"`
// Time is the event's timestamp.
Time time.Time `json:"time"`
// ID is the GUID of this event.
ID string `json:"id"`
// Resources is a list of ARNs of CodeBuild builds that this event pertains to.
Resources []string `json:"resources"`
// Detail contains information specific to a build state-change or
// build phase-change event.
Detail CodeBuildEventDetail `json:"detail"`
}
// CodeBuildEventDetail represents the all details related to the code build event
type CodeBuildEventDetail struct {
BuildStatus CodeBuildPhaseStatus `json:"build-status"`
ProjectName string `json:"project-name"`
BuildID string `json:"build-id"`
AdditionalInformation CodeBuildEventAdditionalInformation `json:"additional-information"`
CurrentPhase CodeBuildPhaseStatus `json:"current-phase"`
CurrentPhaseContext string `json:"current-phase-context"`
Version string `json:"version"`
CompletedPhaseStatus CodeBuildPhaseStatus `json:"completed-phase-status"`
CompletedPhase CodeBuildPhaseStatus `json:"completed-phase"`
CompletedPhaseContext string `json:"completed-phase-context"`
CompletedPhaseDuration DurationSeconds `json:"completed-phase-duration-seconds"`
CompletedPhaseStart CodeBuildTime `json:"completed-phase-start"`
CompletedPhaseEnd CodeBuildTime `json:"completed-phase-end"`
}
//CodeBuildEventAdditionalInformation represents additional informations to the code build event
type CodeBuildEventAdditionalInformation struct {
Artifact CodeBuildArtifact `json:"artifact"`
Environment CodeBuildEnvironment `json:"environment"`
Timeout DurationMinutes `json:"timeout-in-minutes"`
BuildComplete bool `json:"build-complete"`
Initiator string `json:"initiator"`
BuildStartTime CodeBuildTime `json:"build-start-time"`
Source CodeBuildSource `json:"source"`
Logs CodeBuildLogs `json:"logs"`
Phases []CodeBuildPhase `json:"phases"`
}
// CodeBuildArtifact represents the artifact provided to build
type CodeBuildArtifact struct {
MD5Sum string `json:"md5sum"`
SHA256Sum string `json:"sha256sum"`
Location string `json:"location"`
}
// CodeBuildEnvironment represents the environment for a build
type CodeBuildEnvironment struct {
Image string `json:"image"`
PrivilegedMode bool `json:"privileged-mode"`
ComputeType string `json:"compute-type"`
Type string `json:"type"`
EnvironmentVariables []CodeBuildEnvironmentVariable `json:"environment-variables"`
}
// CodeBuildEnvironmentVariable encapsulate environment variables for the code build
type CodeBuildEnvironmentVariable struct {
// Name is the name of the environment variable.
Name string `json:"name"`
// Type is PLAINTEXT or PARAMETER_STORE.
Type string `json:"type"`
// Value is the value of the environment variable.
Value string `json:"value"`
}
// CodeBuildSource represent the code source will be build
type CodeBuildSource struct {
Location string `json:"location"`
Type string `json:"type"`
}
// CodeBuildLogs gives the log details of a code build
type CodeBuildLogs struct {
GroupName string `json:"group-name"`
StreamName string `json:"stream-name"`
DeepLink string `json:"deep-link"`
}
// CodeBuildPhase represents the phase of a build and its details
type CodeBuildPhase struct {
PhaseContext []interface{} `json:"phase-context"`
StartTime CodeBuildTime `json:"start-time"`
EndTime CodeBuildTime `json:"end-time"`
Duration DurationSeconds `json:"duration-in-seconds"`
PhaseType CodeBuildPhaseType `json:"phase-type"`
PhaseStatus CodeBuildPhaseStatus `json:"phase-status"`
}
// CodeBuildTime represents the time of the build
type CodeBuildTime time.Time
const codeBuildTimeFormat = "Jan 2, 2006 3:04:05 PM"
// MarshalJSON converts a given CodeBuildTime to json
func (t CodeBuildTime) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Time(t).Format(codeBuildTimeFormat))
}
// UnmarshalJSON converts a given json to a CodeBuildTime
func (t *CodeBuildTime) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
ts, err := time.Parse(codeBuildTimeFormat, s)
if err != nil {
return err
}
*t = CodeBuildTime(ts)
return nil
}

@ -0,0 +1,80 @@
package events
import (
"time"
)
const (
CodeDeployEventSource = "aws.codedeploy"
CodeDeployDeploymentEventDetailType = "CodeDeploy Deployment State-change Notification"
CodeDeployInstanceEventDetailType = "CodeDeploy Instance State-change Notification"
)
type CodeDeployDeploymentState string
const (
CodeDeployDeploymentStateFailure CodeDeployDeploymentState = "FAILURE"
CodeDeployDeploymentStateReady = "READY"
CodeDeployDeploymentStateStart = "START"
CodeDeployDeploymentStateStop = "STOP"
CodeDeployDeploymentStateSuccess = "SUCCESS"
)
// CodeDeployEvent is documented at:
// https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#acd_event_types
type CodeDeployEvent struct {
// AccountID is the id of the AWS account from which the event originated.
AccountID string `json:"account"`
// Region is the AWS region from which the event originated.
Region string `json:"region"`
// DetailType informs the schema of the Detail field. For deployment state-change
// events, the value should be equal to CodeDeployDeploymentEventDetailType.
// For instance state-change events, the value should be equal to
// CodeDeployInstanceEventDetailType.
DetailType string `json:"detail-type"`
// Source should be equal to CodeDeployEventSource.
Source string `json:"source"`
// Version is the version of the event's schema.
Version string `json:"version"`
// Time is the event's timestamp.
Time time.Time `json:"time"`
// ID is the GUID of this event.
ID string `json:"id"`
// Resources is a list of ARNs of CodeDeploy applications and deployment
// groups that this event pertains to.
Resources []string `json:"resources"`
// Detail contains information specific to a deployment event.
Detail CodeDeployEventDetail `json:"detail"`
}
type CodeDeployEventDetail struct {
// InstanceGroupID is the ID of the instance group.
InstanceGroupID string `json:"instanceGroupId"`
// InstanceID is the id of the instance. This field is non-empty only if
// the DetailType of the complete event is CodeDeployInstanceEventDetailType.
InstanceID string `json:"instanceId,omitempty"`
// Region is the AWS region that the event originated from.
Region string `json:"region"`
// Application is the name of the CodeDeploy application.
Application string `json:"application"`
// DeploymentID is the id of the deployment.
DeploymentID string `json:"deploymentId"`
// State is the new state of the deployment.
State CodeDeployDeploymentState `json:"state"`
// DeploymentGroup is the name of the deployment group.
DeploymentGroup string `json:"deploymentGroup"`
}

@ -0,0 +1,74 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// CodePipelineEvent contains data from an event sent from AWS Codepipeline
type CodePipelineEvent struct {
CodePipelineJob CodePipelineJob `json:"CodePipeline.job"`
}
// CodePipelineJob represents a job from an AWS CodePipeline event
type CodePipelineJob struct {
ID string `json:"id"`
AccountID string `json:"accountId"`
Data CodePipelineData `json:"data"`
}
// CodePipelineData represents a job from an AWS CodePipeline event
type CodePipelineData struct {
ActionConfiguration CodePipelineActionConfiguration `json:"actionConfiguration"`
InputArtifacts []CodePipelineInputArtifact `json:"inputArtifacts"`
OutPutArtifacts []CodePipelineOutputArtifact `json:"outputArtifacts"`
ArtifactCredentials CodePipelineArtifactCredentials `json:"artifactCredentials"`
ContinuationToken string `json:"continuationToken"`
}
// CodePipelineActionConfiguration represents an Action Configuration
type CodePipelineActionConfiguration struct {
Configuration CodePipelineConfiguration `json:"configuration"`
}
// CodePipelineConfiguration represents a configuration for an Action Configuration
type CodePipelineConfiguration struct {
FunctionName string `json:"FunctionName"`
UserParameters string `json:"UserParameters"`
}
// CodePipelineInputArtifact represents an input artifact
type CodePipelineInputArtifact struct {
Location CodePipelineInputLocation `json:"location"`
Revision *string `json:"revision"`
Name string `json:"name"`
}
// CodePipelineInputLocation represents a input location
type CodePipelineInputLocation struct {
S3Location CodePipelineS3Location `json:"s3Location"`
LocationType string `json:"type"`
}
// CodePipelineS3Location represents an s3 input location
type CodePipelineS3Location struct {
BucketName string `json:"bucketName"`
ObjectKey string `json:"objectKey"`
}
// CodePipelineOutputArtifact represents an output artifact
type CodePipelineOutputArtifact struct {
Location CodePipelineInputLocation `json:"location"`
Revision *string `json:"revision"`
Name string `json:"name"`
}
// CodePipelineOutputLocation represents a output location
type CodePipelineOutputLocation struct {
S3Location CodePipelineS3Location `json:"s3Location"`
LocationType string `json:"type"`
}
// CodePipelineArtifactCredentials represents CodePipeline artifact credentials
type CodePipelineArtifactCredentials struct {
SecretAccessKey string `json:"secretAccessKey"`
SessionToken string `json:"sessionToken"`
AccessKeyID string `json:"accessKeyId"`
}

@ -0,0 +1,266 @@
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// CognitoEvent contains data from an event sent from AWS Cognito Sync
type CognitoEvent struct {
DatasetName string `json:"datasetName"`
DatasetRecords map[string]CognitoDatasetRecord `json:"datasetRecords"`
EventType string `json:"eventType"`
IdentityID string `json:"identityId"`
IdentityPoolID string `json:"identityPoolId"`
Region string `json:"region"`
Version int `json:"version"`
}
// CognitoDatasetRecord represents a record from an AWS Cognito Sync event
type CognitoDatasetRecord struct {
NewValue string `json:"newValue"`
OldValue string `json:"oldValue"`
Op string `json:"op"`
}
// CognitoEventUserPoolsPreSignup is sent by AWS Cognito User Pools when a user attempts to register
// (sign up), allowing a Lambda to perform custom validation to accept or deny the registration request
type CognitoEventUserPoolsPreSignup struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsPreSignupRequest `json:"request"`
Response CognitoEventUserPoolsPreSignupResponse `json:"response"`
}
// CognitoEventUserPoolsPreAuthentication is sent by AWS Cognito User Pools when a user submits their information
// to be authenticated, allowing you to perform custom validations to accept or deny the sign in request.
type CognitoEventUserPoolsPreAuthentication struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsPreAuthenticationRequest `json:"request"`
Response CognitoEventUserPoolsPreAuthenticationResponse `json:"response"`
}
// CognitoEventUserPoolsPostConfirmation is sent by AWS Cognito User Pools after a user is confirmed,
// allowing the Lambda to send custom messages or add custom logic.
type CognitoEventUserPoolsPostConfirmation struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsPostConfirmationRequest `json:"request"`
Response CognitoEventUserPoolsPostConfirmationResponse `json:"response"`
}
// CognitoEventUserPoolsPreTokenGen is sent by AWS Cognito User Pools when a user attempts to retrieve
// credentials, allowing a Lambda to perform insert, suppress or override claims
type CognitoEventUserPoolsPreTokenGen struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsPreTokenGenRequest `json:"request"`
Response CognitoEventUserPoolsPreTokenGenResponse `json:"response"`
}
// CognitoEventUserPoolsPostAuthentication is sent by AWS Cognito User Pools after a user is authenticated,
// allowing the Lambda to add custom logic.
type CognitoEventUserPoolsPostAuthentication struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsPostAuthenticationRequest `json:"request"`
Response CognitoEventUserPoolsPostAuthenticationResponse `json:"response"`
}
// CognitoEventUserPoolsMigrateUser is sent by AWS Cognito User Pools when a user does not exist in the
// user pool at the time of sign-in with a password, or in the forgot-password flow.
type CognitoEventUserPoolsMigrateUser struct {
CognitoEventUserPoolsHeader
CognitoEventUserPoolsMigrateUserRequest `json:"request"`
CognitoEventUserPoolsMigrateUserResponse `json:"response"`
}
// CognitoEventUserPoolsCallerContext contains information about the caller
type CognitoEventUserPoolsCallerContext struct {
AWSSDKVersion string `json:"awsSdkVersion"`
ClientID string `json:"clientId"`
}
// CognitoEventUserPoolsHeader contains common data from events sent by AWS Cognito User Pools
type CognitoEventUserPoolsHeader struct {
Version string `json:"version"`
TriggerSource string `json:"triggerSource"`
Region string `json:"region"`
UserPoolID string `json:"userPoolId"`
CallerContext CognitoEventUserPoolsCallerContext `json:"callerContext"`
UserName string `json:"userName"`
}
// CognitoEventUserPoolsPreSignupRequest contains the request portion of a PreSignup event
type CognitoEventUserPoolsPreSignupRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
ValidationData map[string]string `json:"validationData"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsPreSignupResponse contains the response portion of a PreSignup event
type CognitoEventUserPoolsPreSignupResponse struct {
AutoConfirmUser bool `json:"autoConfirmUser"`
AutoVerifyEmail bool `json:"autoVerifyEmail"`
AutoVerifyPhone bool `json:"autoVerifyPhone"`
}
// CognitoEventUserPoolsPreAuthenticationRequest contains the request portion of a PreAuthentication event
type CognitoEventUserPoolsPreAuthenticationRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
ValidationData map[string]string `json:"validationData"`
}
// CognitoEventUserPoolsPreAuthenticationResponse contains the response portion of a PreAuthentication event
type CognitoEventUserPoolsPreAuthenticationResponse struct {
}
// CognitoEventUserPoolsPostConfirmationRequest contains the request portion of a PostConfirmation event
type CognitoEventUserPoolsPostConfirmationRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsPostConfirmationResponse contains the response portion of a PostConfirmation event
type CognitoEventUserPoolsPostConfirmationResponse struct {
}
// CognitoEventUserPoolsPreTokenGenRequest contains request portion of PreTokenGen event
type CognitoEventUserPoolsPreTokenGenRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
GroupConfiguration GroupConfiguration `json:"groupConfiguration"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsPreTokenGenResponse containst the response portion of a PreTokenGen event
type CognitoEventUserPoolsPreTokenGenResponse struct {
ClaimsOverrideDetails ClaimsOverrideDetails `json:"claimsOverrideDetails"`
}
// CognitoEventUserPoolsPostAuthenticationRequest contains the request portion of a PostAuthentication event
type CognitoEventUserPoolsPostAuthenticationRequest struct {
NewDeviceUsed bool `json:"newDeviceUsed"`
UserAttributes map[string]string `json:"userAttributes"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsPostAuthenticationResponse contains the response portion of a PostAuthentication event
type CognitoEventUserPoolsPostAuthenticationResponse struct {
}
// CognitoEventUserPoolsMigrateUserRequest contains the request portion of a MigrateUser event
type CognitoEventUserPoolsMigrateUserRequest struct {
Password string `json:"password"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsMigrateUserResponse contains the response portion of a MigrateUser event
type CognitoEventUserPoolsMigrateUserResponse struct {
UserAttributes map[string]string `json:"userAttributes"`
FinalUserStatus string `json:"finalUserStatus"`
MessageAction string `json:"messageAction"`
DesiredDeliveryMediums []string `json:"desiredDeliveryMediums"`
ForceAliasCreation bool `json:"forceAliasCreation"`
}
// ClaimsOverrideDetails allows lambda to add, suppress or override claims in the token
type ClaimsOverrideDetails struct {
GroupOverrideDetails GroupConfiguration `json:"groupOverrideDetails"`
ClaimsToAddOrOverride map[string]string `json:"claimsToAddOrOverride"`
ClaimsToSuppress []string `json:"claimsToSuppress"`
}
// GroupConfiguration allows lambda to override groups, roles and set a perferred role
type GroupConfiguration struct {
GroupsToOverride []string `json:"groupsToOverride"`
IAMRolesToOverride []string `json:"iamRolesToOverride"`
PreferredRole *string `json:"preferredRole"`
}
// CognitoEventUserPoolsChallengeResult represents a challenge that is presented to the user in the authentication
// process that is underway, along with the corresponding result.
type CognitoEventUserPoolsChallengeResult struct {
ChallengeName string `json:"challengeName"`
ChallengeResult bool `json:"challengeResult"`
ChallengeMetadata string `json:"challengeMetadata"`
}
// CognitoEventUserPoolsDefineAuthChallengeRequest defines auth challenge request parameters
type CognitoEventUserPoolsDefineAuthChallengeRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
Session []*CognitoEventUserPoolsChallengeResult `json:"session"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsDefineAuthChallengeResponse defines auth challenge response parameters
type CognitoEventUserPoolsDefineAuthChallengeResponse struct {
ChallengeName string `json:"challengeName"`
IssueTokens bool `json:"issueTokens"`
FailAuthentication bool `json:"failAuthentication"`
}
// CognitoEventUserPoolsDefineAuthChallenge sent by AWS Cognito User Pools to initiate custom authentication flow
type CognitoEventUserPoolsDefineAuthChallenge struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsDefineAuthChallengeRequest `json:"request"`
Response CognitoEventUserPoolsDefineAuthChallengeResponse `json:"response"`
}
// CognitoEventUserPoolsCreateAuthChallengeRequest defines create auth challenge request parameters
type CognitoEventUserPoolsCreateAuthChallengeRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
ChallengeName string `json:"challengeName"`
Session []*CognitoEventUserPoolsChallengeResult `json:"session"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsCreateAuthChallengeResponse defines create auth challenge response rarameters
type CognitoEventUserPoolsCreateAuthChallengeResponse struct {
PublicChallengeParameters map[string]string `json:"publicChallengeParameters"`
PrivateChallengeParameters map[string]string `json:"privateChallengeParameters"`
ChallengeMetadata string `json:"challengeMetadata"`
}
// CognitoEventUserPoolsCreateAuthChallenge sent by AWS Cognito User Pools to create a challenge to present to the user
type CognitoEventUserPoolsCreateAuthChallenge struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsCreateAuthChallengeRequest `json:"request"`
Response CognitoEventUserPoolsCreateAuthChallengeResponse `json:"response"`
}
// CognitoEventUserPoolsVerifyAuthChallengeRequest defines verify auth challenge request parameters
type CognitoEventUserPoolsVerifyAuthChallengeRequest struct {
UserAttributes map[string]string `json:"userAttributes"`
PrivateChallengeParameters map[string]string `json:"privateChallengeParameters"`
ChallengeAnswer interface{} `json:"challengeAnswer"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsVerifyAuthChallengeResponse defines verify auth challenge response parameters
type CognitoEventUserPoolsVerifyAuthChallengeResponse struct {
AnswerCorrect bool `json:"answerCorrect"`
}
// CognitoEventUserPoolsVerifyAuthChallenge sent by AWS Cognito User Pools to verify if the response from the end user
// for a custom Auth Challenge is valid or not
type CognitoEventUserPoolsVerifyAuthChallenge struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsVerifyAuthChallengeRequest `json:"request"`
Response CognitoEventUserPoolsVerifyAuthChallengeResponse `json:"response"`
}
// CognitoEventUserPoolsCustomMessage is sent by AWS Cognito User Pools before a verification or MFA message is sent,
// allowing a user to customize the message dynamically.
type CognitoEventUserPoolsCustomMessage struct {
CognitoEventUserPoolsHeader
Request CognitoEventUserPoolsCustomMessageRequest `json:"request"`
Response CognitoEventUserPoolsCustomMessageResponse `json:"response"`
}
// CognitoEventUserPoolsCustomMessageRequest contains the request portion of a CustomMessage event
type CognitoEventUserPoolsCustomMessageRequest struct {
UserAttributes map[string]interface{} `json:"userAttributes"`
CodeParameter string `json:"codeParameter"`
UsernameParameter string `json:"usernameParameter"`
ClientMetadata map[string]string `json:"clientMetadata"`
}
// CognitoEventUserPoolsCustomMessageResponse contains the response portion of a CustomMessage event
type CognitoEventUserPoolsCustomMessageResponse struct {
SMSMessage string `json:"smsMessage"`
EmailMessage string `json:"emailMessage"`
EmailSubject string `json:"emailSubject"`
}

@ -0,0 +1,17 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// ConfigEvent contains data from an event sent from AWS Config
type ConfigEvent struct {
AccountID string `json:"accountId"` // The ID of the AWS account that owns the rule
ConfigRuleArn string `json:"configRuleArn"` // The ARN that AWS Config assigned to the rule
ConfigRuleID string `json:"configRuleId"`
ConfigRuleName string `json:"configRuleName"` // The name that you assigned to the rule that caused AWS Config to publish the event
EventLeftScope bool `json:"eventLeftScope"` // A boolean value that indicates whether the AWS resource to be evaluated has been removed from the rule's scope
ExecutionRoleArn string `json:"executionRoleArn"`
InvokingEvent string `json:"invokingEvent"` // If the event is published in response to a resource configuration change, this value contains a JSON configuration item
ResultToken string `json:"resultToken"` // A token that the function must pass to AWS Config with the PutEvaluations call
RuleParameters string `json:"ruleParameters"` // Key/value pairs that the function processes as part of its evaluation logic
Version string `json:"version"`
}

@ -0,0 +1,50 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// ConnectEvent contains the data structure for a Connect event.
type ConnectEvent struct {
Details ConnectDetails `json:"Details"`
Name string `json:"Name"` // The name of the event.
}
// ConnectDetails holds the details of a Connect event
type ConnectDetails struct {
ContactData ConnectContactData `json:"ContactData"`
// The parameters that have been set in the Connect instance at the time of the Lambda invocation.
Parameters map[string]string `json:"Parameters"`
}
// ConnectContactData holds all of the contact information for the user that invoked the Connect event.
type ConnectContactData struct {
// The custom attributes from Connect that the Lambda function was invoked with.
Attributes map[string]string `json:"Attributes"`
Channel string `json:"Channel"`
ContactID string `json:"ContactId"`
CustomerEndpoint ConnectEndpoint `json:"CustomerEndpoint"`
InitialContactID string `json:"InitialContactId"`
// Either: INBOUND/OUTBOUND/TRANSFER/CALLBACK
InitiationMethod string `json:"InitiationMethod"`
PreviousContactID string `json:"PreviousContactId"`
Queue ConnectQueue `json:"Queue"`
SystemEndpoint ConnectEndpoint `json:"SystemEndpoint"`
InstanceARN string `json:"InstanceARN"`
}
// ConnectEndpoint represents routing information.
type ConnectEndpoint struct {
Address string `json:"Address"`
Type string `json:"Type"`
}
// ConnectQueue represents a queue object.
type ConnectQueue struct {
Name string `json:"Name"`
ARN string `json:"ARN"`
}
// ConnectResponse is the structure that Connect expects to get back from Lambda.
// These return values can be used in Connect to perform further routing decisions.
type ConnectResponse map[string]string

@ -0,0 +1,45 @@
package events
import (
"encoding/json"
"math"
"time"
)
type DurationSeconds time.Duration
// UnmarshalJSON converts a given json to a DurationSeconds
func (duration *DurationSeconds) UnmarshalJSON(data []byte) error {
var seconds float64
if err := json.Unmarshal(data, &seconds); err != nil {
return err
}
*duration = DurationSeconds(time.Duration(seconds) * time.Second)
return nil
}
// MarshalJSON converts a given DurationSeconds to json
func (duration DurationSeconds) MarshalJSON() ([]byte, error) {
seconds := time.Duration(duration).Seconds()
return json.Marshal(int64(math.Ceil(seconds)))
}
type DurationMinutes time.Duration
// UnmarshalJSON converts a given json to a DurationMinutes
func (duration *DurationMinutes) UnmarshalJSON(data []byte) error {
var minutes float64
if err := json.Unmarshal(data, &minutes); err != nil {
return err
}
*duration = DurationMinutes(time.Duration(minutes) * time.Minute)
return nil
}
// MarshalJSON converts a given DurationMinutes to json
func (duration DurationMinutes) MarshalJSON() ([]byte, error) {
minutes := time.Duration(duration).Minutes()
return json.Marshal(int64(math.Ceil(minutes)))
}

@ -0,0 +1,134 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// The DynamoDBEvent stream event handled to Lambda
// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update
type DynamoDBEvent struct {
Records []DynamoDBEventRecord `json:"Records"`
}
// DynamoDbEventRecord stores information about each record of a DynamoDb stream event
type DynamoDBEventRecord struct {
// The region in which the GetRecords request was received.
AWSRegion string `json:"awsRegion"`
// The main body of the stream record, containing all of the DynamoDB-specific
// fields.
Change DynamoDBStreamRecord `json:"dynamodb"`
// A globally unique identifier for the event that was recorded in this stream
// record.
EventID string `json:"eventID"`
// The type of data modification that was performed on the DynamoDB table:
//
// * INSERT - a new item was added to the table.
//
// * MODIFY - one or more of an existing item's attributes were modified.
//
// * REMOVE - the item was deleted from the table
EventName string `json:"eventName"`
// The AWS service from which the stream record originated. For DynamoDB Streams,
// this is aws:dynamodb.
EventSource string `json:"eventSource"`
// The version number of the stream record format. This number is updated whenever
// the structure of Record is modified.
//
// Client applications must not assume that eventVersion will remain at a particular
// value, as this number is subject to change at any time. In general, eventVersion
// will only increase as the low-level DynamoDB Streams API evolves.
EventVersion string `json:"eventVersion"`
// The event source ARN of DynamoDB
EventSourceArn string `json:"eventSourceARN"`
// Items that are deleted by the Time to Live process after expiration have
// the following fields:
//
// * Records[].userIdentity.type
//
// "Service"
//
// * Records[].userIdentity.principalId
//
// "dynamodb.amazonaws.com"
UserIdentity *DynamoDBUserIdentity `json:"userIdentity,omitempty"`
}
type DynamoDBUserIdentity struct {
Type string `json:"type"`
PrincipalID string `json:"principalId"`
}
// DynamoDBStreamRecord represents a description of a single data modification that was performed on an item
// in a DynamoDB table.
type DynamoDBStreamRecord struct {
// The approximate date and time when the stream record was created, in UNIX
// epoch time (http://www.epochconverter.com/) format.
ApproximateCreationDateTime SecondsEpochTime `json:"ApproximateCreationDateTime,omitempty"`
// The primary key attribute(s) for the DynamoDB item that was modified.
Keys map[string]DynamoDBAttributeValue `json:"Keys,omitempty"`
// The item in the DynamoDB table as it appeared after it was modified.
NewImage map[string]DynamoDBAttributeValue `json:"NewImage,omitempty"`
// The item in the DynamoDB table as it appeared before it was modified.
OldImage map[string]DynamoDBAttributeValue `json:"OldImage,omitempty"`
// The sequence number of the stream record.
SequenceNumber string `json:"SequenceNumber"`
// The size of the stream record, in bytes.
SizeBytes int64 `json:"SizeBytes"`
// The type of data from the modified DynamoDB item that was captured in this
// stream record.
StreamViewType string `json:"StreamViewType"`
}
type DynamoDBKeyType string
const (
DynamoDBKeyTypeHash DynamoDBKeyType = "HASH"
DynamoDBKeyTypeRange DynamoDBKeyType = "RANGE"
)
type DynamoDBOperationType string
const (
DynamoDBOperationTypeInsert DynamoDBOperationType = "INSERT"
DynamoDBOperationTypeModify DynamoDBOperationType = "MODIFY"
DynamoDBOperationTypeRemove DynamoDBOperationType = "REMOVE"
)
type DynamoDBSharedIteratorType string
const (
DynamoDBShardIteratorTypeTrimHorizon DynamoDBSharedIteratorType = "TRIM_HORIZON"
DynamoDBShardIteratorTypeLatest DynamoDBSharedIteratorType = "LATEST"
DynamoDBShardIteratorTypeAtSequenceNumber DynamoDBSharedIteratorType = "AT_SEQUENCE_NUMBER"
DynamoDBShardIteratorTypeAfterSequenceNumber DynamoDBSharedIteratorType = "AFTER_SEQUENCE_NUMBER"
)
type DynamoDBStreamStatus string
const (
DynamoDBStreamStatusEnabling DynamoDBStreamStatus = "ENABLING"
DynamoDBStreamStatusEnabled DynamoDBStreamStatus = "ENABLED"
DynamoDBStreamStatusDisabling DynamoDBStreamStatus = "DISABLING"
DynamoDBStreamStatusDisabled DynamoDBStreamStatus = "DISABLED"
)
type DynamoDBStreamViewType string
const (
DynamoDBStreamViewTypeNewImage DynamoDBStreamViewType = "NEW_IMAGE" // the entire item, as it appeared after it was modified.
DynamoDBStreamViewTypeOldImage DynamoDBStreamViewType = "OLD_IMAGE" // the entire item, as it appeared before it was modified.
DynamoDBStreamViewTypeNewAndOldImages DynamoDBStreamViewType = "NEW_AND_OLD_IMAGES" // both the new and the old item images of the item.
DynamoDBStreamViewTypeKeysOnly DynamoDBStreamViewType = "KEYS_ONLY" // only the key attributes of the modified item.
)

@ -0,0 +1,59 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"encoding/json"
"time"
)
// SecondsEpochTime serializes a time.Time in JSON as a UNIX epoch time in seconds
type SecondsEpochTime struct {
time.Time
}
// MilliSecondsEpochTime serializes a time.Time in JSON as a UNIX epoch time in milliseconds.
type MilliSecondsEpochTime struct {
time.Time
}
const secondsToNanoSecondsFactor = 1000000000
const milliSecondsToNanoSecondsFactor = 1000000
func (e SecondsEpochTime) MarshalJSON() ([]byte, error) {
// UnixNano() returns the epoch in nanoseconds
unixTime := float64(e.UnixNano()) / float64(secondsToNanoSecondsFactor)
return json.Marshal(unixTime)
}
func (e *SecondsEpochTime) UnmarshalJSON(b []byte) error {
var epoch float64
err := json.Unmarshal(b, &epoch)
if err != nil {
return err
}
epochSec := int64(epoch)
epochNano := int64((epoch - float64(epochSec)) * float64(secondsToNanoSecondsFactor))
// time.Unix(sec, nsec) expects the epoch integral seconds in the first parameter
// and remaining nanoseconds in the second parameter
*e = SecondsEpochTime{time.Unix(epochSec, epochNano)}
return nil
}
func (e MilliSecondsEpochTime) MarshalJSON() ([]byte, error) {
// UnixNano() returns the epoch in nanoseconds
unixTimeMs := e.UnixNano() / milliSecondsToNanoSecondsFactor
return json.Marshal(unixTimeMs)
}
func (e *MilliSecondsEpochTime) UnmarshalJSON(b []byte) error {
var epoch int64
err := json.Unmarshal(b, &epoch)
if err != nil {
return err
}
*e = MilliSecondsEpochTime{time.Unix(epoch/1000, (epoch%1000)*1000000)}
return nil
}

@ -0,0 +1,44 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// KinesisFirehoseEvent represents the input event from Amazon Kinesis Firehose. It is used as the input parameter.
type KinesisFirehoseEvent struct {
InvocationID string `json:"invocationId"`
DeliveryStreamArn string `json:"deliveryStreamArn"`
SourceKinesisStreamArn string `json:"sourceKinesisStreamArn"`
Region string `json:"region"`
Records []KinesisFirehoseEventRecord `json:"records"`
}
type KinesisFirehoseEventRecord struct {
RecordID string `json:"recordId"`
ApproximateArrivalTimestamp MilliSecondsEpochTime `json:"approximateArrivalTimestamp"`
Data []byte `json:"data"`
KinesisFirehoseRecordMetadata KinesisFirehoseRecordMetadata `json:"kinesisRecordMetadata"`
}
// Constants used for describing the transformation result
const (
KinesisFirehoseTransformedStateOk = "Ok"
KinesisFirehoseTransformedStateDropped = "Dropped"
KinesisFirehoseTransformedStateProcessingFailed = "ProcessingFailed"
)
type KinesisFirehoseResponse struct {
Records []KinesisFirehoseResponseRecord `json:"records"`
}
type KinesisFirehoseResponseRecord struct {
RecordID string `json:"recordId"`
Result string `json:"result"` // The status of the transformation. May be TransformedStateOk, TransformedStateDropped or TransformedStateProcessingFailed
Data []byte `json:"data"`
}
type KinesisFirehoseRecordMetadata struct {
ShardID string `json:"shardId"`
PartitionKey string `json:"partitionKey"`
SequenceNumber string `json:"sequenceNumber"`
SubsequenceNumber int64 `json:"subsequenceNumber"`
ApproximateArrivalTimestamp MilliSecondsEpochTime `json:"approximateArrivalTimestamp"`
}

@ -0,0 +1,9 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
type IoTButtonEvent struct {
SerialNumber string `json:"serialNumber"`
ClickType string `json:"clickType"`
BatteryVoltage string `json:"batteryVoltage"`
}

@ -0,0 +1,27 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
type KinesisEvent struct {
Records []KinesisEventRecord `json:"Records"`
}
type KinesisEventRecord struct {
AwsRegion string `json:"awsRegion"`
EventID string `json:"eventID"`
EventName string `json:"eventName"`
EventSource string `json:"eventSource"`
EventSourceArn string `json:"eventSourceARN"`
EventVersion string `json:"eventVersion"`
InvokeIdentityArn string `json:"invokeIdentityArn"`
Kinesis KinesisRecord `json:"kinesis"`
}
type KinesisRecord struct {
ApproximateArrivalTimestamp SecondsEpochTime `json:"approximateArrivalTimestamp"`
Data []byte `json:"data"`
EncryptionType string `json:"encryptionType,omitempty"`
PartitionKey string `json:"partitionKey"`
SequenceNumber string `json:"sequenceNumber"`
KinesisSchemaVersion string `json:"kinesisSchemaVersion"`
}

@ -0,0 +1,28 @@
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
type KinesisAnalyticsOutputDeliveryEvent struct {
InvocationID string `json:"invocationId"`
ApplicationARN string `json:"applicationArn"`
Records []KinesisAnalyticsOutputDeliveryEventRecord `json:"records"`
}
type KinesisAnalyticsOutputDeliveryEventRecord struct {
RecordID string `json:"recordId"`
Data []byte `json:"data"`
}
type KinesisAnalyticsOutputDeliveryResponse struct {
Records []KinesisAnalyticsOutputDeliveryResponseRecord `json:"records"`
}
const (
KinesisAnalyticsOutputDeliveryOK = "Ok"
KinesisAnalyticsOutputDeliveryFailed = "DeliveryFailed"
)
type KinesisAnalyticsOutputDeliveryResponseRecord struct {
RecordID string `json:"recordId"`
Result string `json:"result"` //possible values include Ok and DeliveryFailed
}

@ -0,0 +1,71 @@
package events
type LexEvent struct {
MessageVersion string `json:"messageVersion,omitempty"`
InvocationSource string `json:"invocationSource,omitempty"`
UserID string `json:"userId,omitempty"`
InputTranscript string `json:"inputTranscript,omitempty"`
SessionAttributes SessionAttributes `json:"sessionAttributes,omitempty"`
RequestAttributes map[string]string `json:"requestAttributes,omitempty"`
Bot *LexBot `json:"bot,omitempty"`
OutputDialogMode string `json:"outputDialogMode,omitempty"`
CurrentIntent *LexCurrentIntent `json:"currentIntent,omitempty"`
DialogAction *LexDialogAction `json:"dialogAction,omitempty"`
}
type LexBot struct {
Name string `json:"name,omitempty"`
Alias string `json:"alias,omitempty"`
Version string `json:"version,omitempty"`
}
type LexCurrentIntent struct {
Name string `json:"name,omitempty"`
Slots Slots `json:"slots,omitempty"`
SlotDetails map[string]SlotDetail `json:"slotDetails,omitempty"`
ConfirmationStatus string `json:"confirmationStatus,omitempty"`
}
type SlotDetail struct {
Resolutions []map[string]string `json:"resolutions,omitempty"`
OriginalValue string `json:"originalValue,omitempty"`
}
type LexDialogAction struct {
Type string `json:"type,omitempty"`
FulfillmentState string `json:"fulfillmentState,omitempty"`
Message map[string]string `json:"message,omitempty"`
IntentName string `json:"intentName,omitempty"`
Slots Slots `json:"slots,omitempty"`
SlotToElicit string `json:"slotToElicit,omitempty"`
ResponseCard *LexResponseCard `json:"responseCard,omitempty"`
}
type SessionAttributes map[string]string
type Slots map[string]*string
type LexResponse struct {
SessionAttributes SessionAttributes `json:"sessionAttributes"`
DialogAction LexDialogAction `json:"dialogAction,omitempty"`
}
type LexResponseCard struct {
Version int64 `json:"version,omitempty"`
ContentType string `json:"contentType,omitempty"`
GenericAttachments []Attachment `json:"genericAttachments,omitempty"`
}
type Attachment struct {
Title string `json:"title,omitempty"`
SubTitle string `json:"subTitle,omitempty"`
ImageURL string `json:"imageUrl,omitempty"`
AttachmentLinkURL string `json:"attachmentLinkUrl,omitempty"`
Buttons []map[string]string `json:"buttons,omitempty"`
}
func (h *LexEvent) Clear() {
h.Bot = nil
h.CurrentIntent = nil
h.DialogAction = nil
}

@ -0,0 +1,64 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"time"
)
// S3Event which wrap an array of S3EventRecord
type S3Event struct {
Records []S3EventRecord `json:"Records"`
}
// S3EventRecord which wrap record data
type S3EventRecord struct {
EventVersion string `json:"eventVersion"`
EventSource string `json:"eventSource"`
AWSRegion string `json:"awsRegion"`
EventTime time.Time `json:"eventTime"`
EventName string `json:"eventName"`
PrincipalID S3UserIdentity `json:"userIdentity"`
RequestParameters S3RequestParameters `json:"requestParameters"`
ResponseElements map[string]string `json:"responseElements"`
S3 S3Entity `json:"s3"`
}
type S3UserIdentity struct {
PrincipalID string `json:"principalId"`
}
type S3RequestParameters struct {
SourceIPAddress string `json:"sourceIPAddress"`
}
type S3Entity struct {
SchemaVersion string `json:"s3SchemaVersion"`
ConfigurationID string `json:"configurationId"`
Bucket S3Bucket `json:"bucket"`
Object S3Object `json:"object"`
}
type S3Bucket struct {
Name string `json:"name"`
OwnerIdentity S3UserIdentity `json:"ownerIdentity"`
Arn string `json:"arn"`
}
type S3Object struct {
Key string `json:"key"`
Size int64 `json:"size,omitempty"`
URLDecodedKey string `json:"urlDecodedKey"`
VersionID string `json:"versionId"`
ETag string `json:"eTag"`
Sequencer string `json:"sequencer"`
}
type S3TestEvent struct {
Service string `json:"Service"`
Bucket string `json:"Bucket"`
Event string `json:"Event"`
Time time.Time `json:"Time"`
RequestID string `json:"RequestId"`
HostID string `json:"HostId"`
}

@ -0,0 +1,39 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// S3BatchJobEvent encapsulates the detail of a s3 batch job
type S3BatchJobEvent struct {
InvocationSchemaVersion string `json:"invocationSchemaVersion"`
InvocationID string `json:"invocationId"`
Job S3BatchJob `json:"job"`
Tasks []S3BatchJobTask `json:"tasks"`
}
// S3BatchJob whichs have the job id
type S3BatchJob struct {
ID string `json:"id"`
}
// S3BatchJobTask represents one task in the s3 batch job and have all task details
type S3BatchJobTask struct {
TaskID string `json:"taskId"`
S3Key string `json:"s3Key"`
S3VersionID string `json:"s3VersionId"`
S3BucketARN string `json:"s3BucketArn"`
}
// S3BatchJobResponse is the response of a iven s3 batch job with the results
type S3BatchJobResponse struct {
InvocationSchemaVersion string `json:"invocationSchemaVersion"`
TreatMissingKeysAs string `json:"treatMissingKeysAs"`
InvocationID string `json:"invocationId"`
Results []S3BatchJobResult `json:"results"`
}
// S3BatchJobResult represents the result of a given task
type S3BatchJobResult struct {
TaskID string `json:"taskId"`
ResultCode string `json:"resultCode"`
ResultString string `json:"resultString"`
}

@ -0,0 +1,95 @@
package events
import "time"
// SimpleEmailEvent is the outer structure of an event sent via SES.
type SimpleEmailEvent struct {
Records []SimpleEmailRecord `json:"Records"`
}
type SimpleEmailRecord struct {
EventVersion string `json:"eventVersion"`
EventSource string `json:"eventSource"`
SES SimpleEmailService `json:"ses"`
}
type SimpleEmailService struct {
Mail SimpleEmailMessage `json:"mail"`
Receipt SimpleEmailReceipt `json:"receipt"`
}
type SimpleEmailMessage struct {
CommonHeaders SimpleEmailCommonHeaders `json:"commonHeaders"`
Source string `json:"source"`
Timestamp time.Time `json:"timestamp"`
Destination []string `json:"destination"`
Headers []SimpleEmailHeader `json:"headers"`
HeadersTruncated bool `json:"headersTruncated"`
MessageID string `json:"messageId"`
}
type SimpleEmailReceipt struct {
Recipients []string `json:"recipients"`
Timestamp time.Time `json:"timestamp"`
SpamVerdict SimpleEmailVerdict `json:"spamVerdict"`
DKIMVerdict SimpleEmailVerdict `json:"dkimVerdict"`
DMARCVerdict SimpleEmailVerdict `json:"dmarcVerdict"`
DMARCPolicy string `json:"dmarcPolicy"`
SPFVerdict SimpleEmailVerdict `json:"spfVerdict"`
VirusVerdict SimpleEmailVerdict `json:"virusVerdict"`
Action SimpleEmailReceiptAction `json:"action"`
ProcessingTimeMillis int64 `json:"processingTimeMillis"`
}
type SimpleEmailHeader struct {
Name string `json:"name"`
Value string `json:"value"`
}
type SimpleEmailCommonHeaders struct {
From []string `json:"from"`
To []string `json:"to"`
ReturnPath string `json:"returnPath"`
MessageID string `json:"messageId"`
Date string `json:"date"`
Subject string `json:"subject"`
}
// SimpleEmailReceiptAction is a logical union of fields present in all action
// Types. For example, the FunctionARN and InvocationType fields are only
// present for the Lambda Type, and the BucketName and ObjectKey fields are only
// present for the S3 Type.
type SimpleEmailReceiptAction struct {
Type string `json:"type"`
TopicARN string `json:"topicArn,omitempty"`
BucketName string `json:"bucketName,omitempty"`
ObjectKey string `json:"objectKey,omitempty"`
SMTPReplyCode string `json:"smtpReplyCode,omitempty"`
StatusCode string `json:"statusCode,omitempty"`
Message string `json:"message,omitempty"`
Sender string `json:"sender,omitempty"`
InvocationType string `json:"invocationType,omitempty"`
FunctionARN string `json:"functionArn,omitempty"`
OrganizationARN string `json:"organizationArn,omitempty"`
}
type SimpleEmailVerdict struct {
Status string `json:"status"`
}
// SimpleEmailDispositionValue enumeration representing the dispostition value for SES
type SimpleEmailDispositionValue string
const (
// SimpleEmailContinue represents the CONTINUE disposition which tells the SES Rule Set to continue to the next rule
SimpleEmailContinue SimpleEmailDispositionValue = "CONTINUE"
// SimpleEmailStopRule represents the STOP_RULE disposition which tells the SES Rule Set to stop processing this rule and continue to the next
SimpleEmailStopRule SimpleEmailDispositionValue = "STOP_RULE"
// SimpleEmailStopRuleSet represents the STOP_RULE_SET disposition which tells the SES Rule SEt to stop processing all rules
SimpleEmailStopRuleSet SimpleEmailDispositionValue = "STOP_RULE_SET"
)
// SimpleEmailDisposition disposition return for SES to control rule functions
type SimpleEmailDisposition struct {
Disposition SimpleEmailDispositionValue `json:"disposition"`
}

@ -0,0 +1,32 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"time"
)
type SNSEvent struct {
Records []SNSEventRecord `json:"Records"`
}
type SNSEventRecord struct {
EventVersion string `json:"EventVersion"`
EventSubscriptionArn string `json:"EventSubscriptionArn"`
EventSource string `json:"EventSource"`
SNS SNSEntity `json:"Sns"`
}
type SNSEntity struct {
Signature string `json:"Signature"`
MessageID string `json:"MessageId"`
Type string `json:"Type"`
TopicArn string `json:"TopicArn"`
MessageAttributes map[string]interface{} `json:"MessageAttributes"`
SignatureVersion string `json:"SignatureVersion"`
Timestamp time.Time `json:"Timestamp"`
SigningCertURL string `json:"SigningCertUrl"`
Message string `json:"Message"`
UnsubscribeURL string `json:"UnsubscribeUrl"`
Subject string `json:"Subject"`
}

@ -0,0 +1,28 @@
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
type SQSEvent struct {
Records []SQSMessage `json:"Records"`
}
type SQSMessage struct {
MessageId string `json:"messageId"`
ReceiptHandle string `json:"receiptHandle"`
Body string `json:"body"`
Md5OfBody string `json:"md5OfBody"`
Md5OfMessageAttributes string `json:"md5OfMessageAttributes"`
Attributes map[string]string `json:"attributes"`
MessageAttributes map[string]SQSMessageAttribute `json:"messageAttributes"`
EventSourceARN string `json:"eventSourceARN"`
EventSource string `json:"eventSource"`
AWSRegion string `json:"awsRegion"`
}
type SQSMessageAttribute struct {
StringValue *string `json:"stringValue,omitempty"`
BinaryValue []byte `json:"binaryValue,omitempty"`
StringListValues []string `json:"stringListValues"`
BinaryListValues [][]byte `json:"binaryListValues"`
DataType string `json:"dataType"`
}

@ -0,0 +1,3 @@
# Overview
[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/lambda?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/lambda)

@ -0,0 +1,62 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"log"
"net"
"net/rpc"
"os"
)
// Start takes a handler and talks to an internal Lambda endpoint to pass requests to the handler. If the
// handler does not match one of the supported types an appropriate error message will be returned to the caller.
// Start blocks, and does not return after being called.
//
// Rules:
//
// * handler must be a function
// * handler may take between 0 and two arguments.
// * if there are two arguments, the first argument must satisfy the "context.Context" interface.
// * handler may return between 0 and two arguments.
// * if there are two return values, the second argument must be an error.
// * if there is one return value it must be an error.
//
// Valid function signatures:
//
// func ()
// func () error
// func (TIn) error
// func () (TOut, error)
// func (TIn) (TOut, error)
// func (context.Context) error
// func (context.Context, TIn) error
// func (context.Context) (TOut, error)
// func (context.Context, TIn) (TOut, error)
//
// Where "TIn" and "TOut" are types compatible with the "encoding/json" standard library.
// See https://golang.org/pkg/encoding/json/#Unmarshal for how deserialization behaves
func Start(handler interface{}) {
wrappedHandler := NewHandler(handler)
StartHandler(wrappedHandler)
}
// StartHandler takes in a Handler wrapper interface which can be implemented either by a
// custom function or a struct.
//
// Handler implementation requires a single "Invoke()" function:
//
// func Invoke(context.Context, []byte) ([]byte, error)
func StartHandler(handler Handler) {
port := os.Getenv("_LAMBDA_SERVER_PORT")
lis, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
log.Fatal(err)
}
err = rpc.Register(NewFunction(handler))
if err != nil {
log.Fatal("failed to register handler function")
}
rpc.Accept(lis)
log.Fatal("accept should not have returned")
}

@ -0,0 +1,97 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"context"
"encoding/json"
"os"
"reflect"
"time"
"github.com/aws/aws-lambda-go/lambda/messages"
"github.com/aws/aws-lambda-go/lambdacontext"
)
// Function struct which wrap the Handler
type Function struct {
handler Handler
}
// NewFunction which creates a Function with a given Handler
func NewFunction(handler Handler) *Function {
return &Function{handler: handler}
}
// Ping method which given a PingRequest and a PingResponse parses the PingResponse
func (fn *Function) Ping(req *messages.PingRequest, response *messages.PingResponse) error {
*response = messages.PingResponse{}
return nil
}
// Invoke method try to perform a command given an InvokeRequest and an InvokeResponse
func (fn *Function) Invoke(req *messages.InvokeRequest, response *messages.InvokeResponse) error {
defer func() {
if err := recover(); err != nil {
panicInfo := getPanicInfo(err)
response.Error = &messages.InvokeResponse_Error{
Message: panicInfo.Message,
Type: getErrorType(err),
StackTrace: panicInfo.StackTrace,
ShouldExit: true,
}
}
}()
deadline := time.Unix(req.Deadline.Seconds, req.Deadline.Nanos).UTC()
invokeContext, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
lc := &lambdacontext.LambdaContext{
AwsRequestID: req.RequestId,
InvokedFunctionArn: req.InvokedFunctionArn,
Identity: lambdacontext.CognitoIdentity{
CognitoIdentityID: req.CognitoIdentityId,
CognitoIdentityPoolID: req.CognitoIdentityPoolId,
},
}
if len(req.ClientContext) > 0 {
if err := json.Unmarshal(req.ClientContext, &lc.ClientContext); err != nil {
response.Error = lambdaErrorResponse(err)
return nil
}
}
invokeContext = lambdacontext.NewContext(invokeContext, lc)
invokeContext = context.WithValue(invokeContext, "x-amzn-trace-id", req.XAmznTraceId)
os.Setenv("_X_AMZN_TRACE_ID", req.XAmznTraceId)
payload, err := fn.handler.Invoke(invokeContext, req.Payload)
if err != nil {
response.Error = lambdaErrorResponse(err)
return nil
}
response.Payload = payload
return nil
}
func getErrorType(err interface{}) string {
errorType := reflect.TypeOf(err)
if errorType.Kind() == reflect.Ptr {
return errorType.Elem().Name()
}
return errorType.Name()
}
func lambdaErrorResponse(invokeError error) *messages.InvokeResponse_Error {
var errorName string
if errorType := reflect.TypeOf(invokeError); errorType.Kind() == reflect.Ptr {
errorName = errorType.Elem().Name()
} else {
errorName = errorType.Name()
}
return &messages.InvokeResponse_Error{
Message: invokeError.Error(),
Type: errorName,
}
}

@ -0,0 +1,144 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"context"
"encoding/json"
"fmt"
"reflect"
"github.com/aws/aws-lambda-go/lambda/handlertrace"
)
type Handler interface {
Invoke(ctx context.Context, payload []byte) ([]byte, error)
}
// lambdaHandler is the generic function type
type lambdaHandler func(context.Context, []byte) (interface{}, error)
// Invoke calls the handler, and serializes the response.
// If the underlying handler returned an error, or an error occurs during serialization, error is returned.
func (handler lambdaHandler) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
response, err := handler(ctx, payload)
if err != nil {
return nil, err
}
responseBytes, err := json.Marshal(response)
if err != nil {
return nil, err
}
return responseBytes, nil
}
func errorHandler(e error) lambdaHandler {
return func(ctx context.Context, event []byte) (interface{}, error) {
return nil, e
}
}
func validateArguments(handler reflect.Type) (bool, error) {
handlerTakesContext := false
if handler.NumIn() > 2 {
return false, fmt.Errorf("handlers may not take more than two arguments, but handler takes %d", handler.NumIn())
} else if handler.NumIn() > 0 {
contextType := reflect.TypeOf((*context.Context)(nil)).Elem()
argumentType := handler.In(0)
handlerTakesContext = argumentType.Implements(contextType)
if handler.NumIn() > 1 && !handlerTakesContext {
return false, fmt.Errorf("handler takes two arguments, but the first is not Context. got %s", argumentType.Kind())
}
}
return handlerTakesContext, nil
}
func validateReturns(handler reflect.Type) error {
errorType := reflect.TypeOf((*error)(nil)).Elem()
switch n := handler.NumOut(); {
case n > 2:
return fmt.Errorf("handler may not return more than two values")
case n > 1:
if !handler.Out(1).Implements(errorType) {
return fmt.Errorf("handler returns two values, but the second does not implement error")
}
case n == 1:
if !handler.Out(0).Implements(errorType) {
return fmt.Errorf("handler returns a single value, but it does not implement error")
}
}
return nil
}
// NewHandler creates a base lambda handler from the given handler function. The
// returned Handler performs JSON deserialization and deserialization, and
// delegates to the input handler function. The handler function parameter must
// satisfy the rules documented by Start. If handlerFunc is not a valid
// handler, the returned Handler simply reports the validation error.
func NewHandler(handlerFunc interface{}) Handler {
if handlerFunc == nil {
return errorHandler(fmt.Errorf("handler is nil"))
}
handler := reflect.ValueOf(handlerFunc)
handlerType := reflect.TypeOf(handlerFunc)
if handlerType.Kind() != reflect.Func {
return errorHandler(fmt.Errorf("handler kind %s is not %s", handlerType.Kind(), reflect.Func))
}
takesContext, err := validateArguments(handlerType)
if err != nil {
return errorHandler(err)
}
if err := validateReturns(handlerType); err != nil {
return errorHandler(err)
}
return lambdaHandler(func(ctx context.Context, payload []byte) (interface{}, error) {
trace := handlertrace.FromContext(ctx)
// construct arguments
var args []reflect.Value
if takesContext {
args = append(args, reflect.ValueOf(ctx))
}
if (handlerType.NumIn() == 1 && !takesContext) || handlerType.NumIn() == 2 {
eventType := handlerType.In(handlerType.NumIn() - 1)
event := reflect.New(eventType)
if err := json.Unmarshal(payload, event.Interface()); err != nil {
return nil, err
}
if nil != trace.RequestEvent {
trace.RequestEvent(ctx, event.Elem().Interface())
}
args = append(args, event.Elem())
}
response := handler.Call(args)
// convert return values into (interface{}, error)
var err error
if len(response) > 0 {
if errVal, ok := response[len(response)-1].Interface().(error); ok {
err = errVal
}
}
var val interface{}
if len(response) > 1 {
val = response[0].Interface()
if nil != trace.ResponseEvent {
trace.ResponseEvent(ctx, val)
}
}
return val, err
})
}

@ -0,0 +1,44 @@
// Package handlertrace allows middleware authors using lambda.NewHandler to
// instrument request and response events.
package handlertrace
import (
"context"
)
// HandlerTrace allows handlers which wrap the return value of lambda.NewHandler
// to access to the request and response events.
type HandlerTrace struct {
RequestEvent func(context.Context, interface{})
ResponseEvent func(context.Context, interface{})
}
func callbackCompose(f1, f2 func(context.Context, interface{})) func(context.Context, interface{}) {
return func(ctx context.Context, event interface{}) {
if nil != f1 {
f1(ctx, event)
}
if nil != f2 {
f2(ctx, event)
}
}
}
type handlerTraceKey struct{}
// NewContext adds callbacks to the provided context which allows handlers which
// wrap the return value of lambda.NewHandler to access to the request and
// response events.
func NewContext(ctx context.Context, trace HandlerTrace) context.Context {
existing := FromContext(ctx)
return context.WithValue(ctx, handlerTraceKey{}, HandlerTrace{
RequestEvent: callbackCompose(existing.RequestEvent, trace.RequestEvent),
ResponseEvent: callbackCompose(existing.ResponseEvent, trace.ResponseEvent),
})
}
// FromContext returns the HandlerTrace associated with the provided context.
func FromContext(ctx context.Context) HandlerTrace {
trace, _ := ctx.Value(handlerTraceKey{}).(HandlerTrace)
return trace
}

@ -0,0 +1,3 @@
# Overview
[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/lambda/messages?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/lambda/messages)

@ -0,0 +1,43 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package messages
type PingRequest struct {
}
type PingResponse struct {
}
type InvokeRequest_Timestamp struct {
Seconds int64
Nanos int64
}
type InvokeRequest struct {
Payload []byte
RequestId string
XAmznTraceId string
Deadline InvokeRequest_Timestamp
InvokedFunctionArn string
CognitoIdentityId string
CognitoIdentityPoolId string
ClientContext []byte
}
type InvokeResponse struct {
Payload []byte
Error *InvokeResponse_Error
}
type InvokeResponse_Error struct {
Message string
Type string
StackTrace []*InvokeResponse_Error_StackFrame
ShouldExit bool
}
type InvokeResponse_Error_StackFrame struct {
Path string `json:"path"`
Line int32 `json:"line"`
Label string `json:"label"`
}

@ -0,0 +1,99 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"fmt"
"runtime"
"strings"
"github.com/aws/aws-lambda-go/lambda/messages"
)
type panicInfo struct {
Message string // Value passed to panic call, converted to string
StackTrace []*messages.InvokeResponse_Error_StackFrame // Stack trace of the panic
}
func getPanicInfo(value interface{}) panicInfo {
message := getPanicMessage(value)
stack := getPanicStack()
return panicInfo{Message: message, StackTrace: stack}
}
func getPanicMessage(value interface{}) string {
return fmt.Sprintf("%v", value)
}
var defaultErrorFrameCount = 32
func getPanicStack() []*messages.InvokeResponse_Error_StackFrame {
s := make([]uintptr, defaultErrorFrameCount)
const framesToHide = 3 // this (getPanicStack) -> getPanicInfo -> handler defer func
n := runtime.Callers(framesToHide, s)
if n == 0 {
return make([]*messages.InvokeResponse_Error_StackFrame, 0)
}
s = s[:n]
return convertStack(s)
}
func convertStack(s []uintptr) []*messages.InvokeResponse_Error_StackFrame {
var converted []*messages.InvokeResponse_Error_StackFrame
frames := runtime.CallersFrames(s)
for {
frame, more := frames.Next()
formattedFrame := formatFrame(frame)
converted = append(converted, formattedFrame)
if !more {
break
}
}
return converted
}
func formatFrame(inputFrame runtime.Frame) *messages.InvokeResponse_Error_StackFrame {
path := inputFrame.File
line := int32(inputFrame.Line)
label := inputFrame.Function
// Strip GOPATH from path by counting the number of seperators in label & path
//
// For example given this:
// GOPATH = /home/user
// path = /home/user/src/pkg/sub/file.go
// label = pkg/sub.Type.Method
//
// We want to set:
// path = pkg/sub/file.go
// label = Type.Method
i := len(path)
for n, g := 0, strings.Count(label, "/")+2; n < g; n++ {
i = strings.LastIndex(path[:i], "/")
if i == -1 {
// Something went wrong and path has less seperators than we expected
// Abort and leave i as -1 to counteract the +1 below
break
}
}
path = path[i+1:] // Trim the initial /
// Strip the path from the function name as it's already in the path
label = label[strings.LastIndex(label, "/")+1:]
// Likewise strip the package name
label = label[strings.Index(label, ".")+1:]
return &messages.InvokeResponse_Error_StackFrame{
Path: path,
Line: line,
Label: label,
}
}

@ -0,0 +1,3 @@
# Overview
[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/lambdacontext?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/lambdacontext)

@ -0,0 +1,89 @@
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Helpers for accessing context information from an Invoke request. Context information
// is stored in a https://golang.org/pkg/context/#Context. The functions FromContext and NewContext
// are used to retrieving and inserting an isntance of LambdaContext.
package lambdacontext
import (
"context"
"os"
"strconv"
)
// LogGroupName is the name of the log group that contains the log streams of the current Lambda Function
var LogGroupName string
// LogStreamName name of the log stream that the current Lambda Function's logs will be sent to
var LogStreamName string
// FunctionName the name of the current Lambda Function
var FunctionName string
// MemoryLimitInMB is the configured memory limit for the current instance of the Lambda Function
var MemoryLimitInMB int
// FunctionVersion is the published version of the current instance of the Lambda Function
var FunctionVersion string
func init() {
LogGroupName = os.Getenv("AWS_LAMBDA_LOG_GROUP_NAME")
LogStreamName = os.Getenv("AWS_LAMBDA_LOG_STREAM_NAME")
FunctionName = os.Getenv("AWS_LAMBDA_FUNCTION_NAME")
if limit, err := strconv.Atoi(os.Getenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE")); err != nil {
MemoryLimitInMB = 0
} else {
MemoryLimitInMB = limit
}
FunctionVersion = os.Getenv("AWS_LAMBDA_FUNCTION_VERSION")
}
// ClientApplication is metadata about the calling application.
type ClientApplication struct {
InstallationID string `json:"installation_id"`
AppTitle string `json:"app_title"`
AppVersionCode string `json:"app_version_code"`
AppPackageName string `json:"app_package_name"`
}
// ClientContext is information about the client application passed by the calling application.
type ClientContext struct {
Client ClientApplication
Env map[string]string `json:"env"`
Custom map[string]string `json:"custom"`
}
// CognitoIdentity is the cognito identity used by the calling application.
type CognitoIdentity struct {
CognitoIdentityID string
CognitoIdentityPoolID string
}
// LambdaContext is the set of metadata that is passed for every Invoke.
type LambdaContext struct {
AwsRequestID string
InvokedFunctionArn string
Identity CognitoIdentity
ClientContext ClientContext
}
// An unexported type to be used as the key for types in this package.
// This prevents collisions with keys defined in other packages.
type key struct{}
// The key for a LambdaContext in Contexts.
// Users of this package must use lambdacontext.NewContext and lambdacontext.FromContext
// instead of using this key directly.
var contextKey = &key{}
// NewContext returns a new Context that carries value lc.
func NewContext(parent context.Context, lc *LambdaContext) context.Context {
return context.WithValue(parent, contextKey, lc)
}
// FromContext returns the LambdaContext value stored in ctx, if any.
func FromContext(ctx context.Context) (*LambdaContext, bool) {
lc, ok := ctx.Value(contextKey).(*LambdaContext)
return lc, ok
}

@ -65,6 +65,13 @@ github.com/armon/go-metrics
github.com/armon/go-metrics/prometheus
# github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496
github.com/asaskevich/govalidator
# github.com/aws/aws-lambda-go v1.17.0
## explicit
github.com/aws/aws-lambda-go/events
github.com/aws/aws-lambda-go/lambda
github.com/aws/aws-lambda-go/lambda/handlertrace
github.com/aws/aws-lambda-go/lambda/messages
github.com/aws/aws-lambda-go/lambdacontext
# github.com/aws/aws-sdk-go v1.33.12
github.com/aws/aws-sdk-go/aws
github.com/aws/aws-sdk-go/aws/arn

Loading…
Cancel
Save