lambda-go-api-proxy makes it easy to port APIs written with Go frameworks such as Gin to AWS Lambda and Amazon API Gateway.

Overview

AWS Lambda Go Api Proxy Build Status

aws-lambda-go-api-proxy makes it easy to run Golang APIs written with frameworks such as Gin with AWS Lambda and Amazon API Gateway.

Getting started

The first step is to install the required dependencies

# First, we install the Lambda go libraries
$ go get github.com/aws/aws-lambda-go/events
$ go get github.com/aws/aws-lambda-go/lambda

# Next, we install the core library
$ go get github.com/awslabs/aws-lambda-go-api-proxy/...

Following the instructions from the Lambda documentation, we need to declare a Handler method for our main package. We will declare a ginadapter.GinLambda object in the global scope, initialized once it in the Handler with all its API methods, and then use the Proxy method to translate requests and responses

package main

import (
	"log"
	"context"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/awslabs/aws-lambda-go-api-proxy/gin"
	"github.com/gin-gonic/gin"
)

var ginLambda *ginadapter.GinLambda

func init() {
	// stdout and stderr are sent to AWS CloudWatch Logs
	log.Printf("Gin cold start")
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	ginLambda = ginadapter.New(r)
}

func Handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	// If no name is provided in the HTTP request body, throw an error
	return ginLambda.ProxyWithContext(ctx, req)
}

func main() {
	lambda.Start(Handler)
}

Other frameworks

This package also supports Negroni, GorillaMux, and plain old HandlerFunc - take a look at the code in their respective sub-directories. All packages implement the Proxy method exactly like our Gin sample above.

Deploying the sample

We have included a SAM template with our sample application. You can use the AWS CLI to quickly deploy the application in your AWS account.

First, build the sample application by running make from the aws-lambda-go-api-proxy directory.

$ cd aws-lambda-go-api-proxy
$ make

The make process should generate a main.zip file in the sample folder. You can now use the AWS CLI to prepare the deployment for AWS Lambda and Amazon API Gateway.

$ cd sample
$ aws cloudformation package --template-file sam.yaml --output-template-file output-sam.yaml --s3-bucket YOUR_DEPLOYMENT_BUCKET
$ aws cloudformation deploy --template-file output-sam.yaml --stack-name YOUR_STACK_NAME --capabilities CAPABILITY_IAM

Using the CloudFormation console, you can find the URL for the newly created API endpoint in the Outputs tab of the sample stack - it looks sample like this: https://xxxxxxxxx.execute-api.xx-xxxx-x.amazonaws.com/Prod/pets. Open a browser window and try to call the URL.

API Gateway context and stage variables

The RequestAccessor object, and therefore GinLambda, automatically marshals the API Gateway request context and stage variables objects and stores them in custom headers in the request: X-GinLambda-ApiGw-Context and X-GinLambda-ApiGw-StageVars. While you could manually unmarshal the json content into the events.APIGatewayProxyRequestContext and map[string]string objects, the library exports two utility methods to give you easy access to the data.

// the methods are available in your instance of the GinLambda
// object and receive the http.Request object
apiGwContext := ginLambda.GetAPIGatewayContext(c.Request)
apiGwStageVars := ginLambda.GetAPIGatewayStageVars(c.Request)

// you can access the properties of the context directly
log.Println(apiGwContext.RequestID)
log.Println(apiGwContext.Stage)

// stage variables are stored in a map[string]string
stageVarValue := apiGwStageVars["MyStageVar"]

Supporting other frameworks

The aws-lambda-go-api-proxy, alongside the various adapters, declares a core package. The core package, contains utility methods and interfaces to translate API Gateway proxy events into Go's default http.Request and http.ResponseWriter objects.

You can see that the ginlambda.go file extends the RequestAccessor struct defined in the request.go file. RequestAccessor gives you access to the ProxyEventToHTTPRequest() method.

The GinLambda object is initialized with an instance of gin.Engine. gin.Engine implements methods defined in the http.Handler interface.

The Proxy method of the GinLambda object simply receives the events.APIGatewayProxyRequest object and uses the ProxyEventToHTTPRequest() method to convert it into an http.Request object. Next, it creates a new ProxyResponseWriter object (defined in the response.go) file and passes both request and response writer to the ServeHTTP method of the gin.Engine.

The ProxyResponseWriter exports a method called GetProxyResponse() to generate an events.APIGatewayProxyResponse object from the data written to the response writer.

Support for frameworks other than Gin can rely on the same methods from the core package and swap the gin.Engine object for the relevant framework's object.

License

This library is licensed under the Apache 2.0 License.

Comments
  • At fiber adapter, to add header method is changed 'Add(k, v)' to 'Set(k, v)'

    At fiber adapter, to add header method is changed 'Add(k, v)' to 'Set(k, v)'

    Issue #, if available: #88

    Description of changes: Fiber lambda adapter cannot pass specific header 'Content-Type', 'User-Agent'. So, I change method Add to Set.

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by drakejin 16
  • Request for overriding DefaultServerAddress

    Request for overriding DefaultServerAddress

    The proxied http.Request URL will currently always start with https://aws-serverless-go-api.com because of the way the the URL is created here: https://github.com/awslabs/aws-lambda-go-api-proxy/blob/master/core/request.go#L137

    This is an issue when API Gateway is configured to use a custom domain. For instance Gorrila MUX will redirect the client to a 'clean' version of the URL path. It makes use of the request URL to construct the redirect URL in de HTTP response: https://github.com/gorilla/mux/blob/master/mux.go#L125-L137

    Could you please create the ability to override the server address? Another option would be to use the value of request.host in the API Gateway Proxy Request Event.

    opened by jeroenkoknl 11
  • Upgrade github.com/go-chi/chi

    Upgrade github.com/go-chi/chi

    Issue #, if available:

    Description of changes: Upgrading github.com/go-chi/chi to v5, which is latest and also supports go mod

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by vishal24tuniki 10
  • Support for echo router v4

    Support for echo router v4

    Hello! Could we upgrade the echo module to support version 4? I have a dependency that returns a v4 echo router (and it seems to be the favored version on the github page), but I can't integrate it with the aws-lambda-go-api-proxy. I can do a very quick pull request that either adds support for both versions, or alternatively changes the import to github.com/labstack/echo/v4 if you'd like.

    Thanks!

    opened by jackwellsxyz 9
  • Add support for multi-value headers in API Gateway

    Add support for multi-value headers in API Gateway

    Since November 2018, AWS supported multi-value parameters in API Gateway which includes multi-value headers. We would need to add support for this feature. One notable use case of this feature is allowing Lambda functions to return multiple "Set-Cookie" header to client. Currently only the last cookie is captured by the library.

    Based on that AWS articles, looks like we can just get rid of Headers field entirely and replaced it by MultiValueHeaders, even for single-value headers.

    opened by huyphan 8
  • Invalid Iris dependency

    Invalid Iris dependency

    Since today I'm unable to build my go application using aws-lambda-go-api-proxy due to an invalid version of the iris dependency.

    go test ./... -covermode=count -count=1
    go: github.com/awslabs/[email protected] requires
    	github.com/kataras/[email protected]+incompatible: reading github.com/kataras/iris/go.mod at revision v11.1.1: unknown revision v11.1.1
    

    And after looking into the github.com/kataras/iris, there is no v11.1.1 version. At this point, I'm not sure how did it work before - did the github.com/kataras/[email protected] got deleted from their github, or am I missing something?

    opened by adam-debkowski 7
  • 🚀 Add Fiber

    🚀 Add Fiber

    Fiber
    Fiber is an Express inspired web framework built on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development with zero memory allocation and performance in mind.

    === RUN   TestFiber
    Running Suite: Fiber Suite
    ==========================
    Random Seed: 1594252703
    Will run 1 of 1 specs
    
    2020/07/09 07:58:23 Starting test
    2020/07/09 07:58:23 Handler!!
    •
    Ran 1 of 1 Specs in 0.001 seconds
    SUCCESS! -- 1 Passed | 0 Failed | 0 Pending | 0 Skipped
    --- PASS: TestFiber (0.00s)
    PASS
    

    Thanks @sapessi 👍

    opened by Fenny 6
  • Infer domain name from request context

    Infer domain name from request context

    Issue #, if available: Fixes: https://github.com/awslabs/aws-lambda-go-api-proxy/issues/46 Fixes: https://github.com/awslabs/aws-lambda-go-api-proxy/issues/13 Description of changes: aws-lambda-go recently added support for DomainName property in RequestContext. We want to revert to that domain name rather than aws-serverless-go-api.com. This change is backwards compatible, in that, people using GO_API_HOST env variable can still use that.

    I wasn't able to update dependencies properly with govendor because it keeps thowing an error when I try to do govendor get github.com/aws/[email protected]:

    go: finding module for package github.com/aws/aws-lambda-go
    can't load package: package github.com/aws/aws-lambda-go: module github.com/aws/[email protected] found (v1.17.0), but does not contain package github.com/aws/aws-lambda-go
    Error: exit status 1
    

    Please update dependencies manually and publish them here when reviewing this PR!

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by RaeesBhatti 6
  • Cannot go get based on the installation instruction

    Cannot go get based on the installation instruction

    I did go get github.com/awslabs/aws-lambda-go-api-proxy like in the README.md but it shows error

    can't load package: package github.com/awslabs/aws-lambda-go-api-proxy: no Go files in /Users/user/Code/golang/src/github.com/awslabs/aws-lambda-go-api-proxy

    Did I miss something?

    opened by adhatama 6
  • Properly set apigwv2 response headers

    Properly set apigwv2 response headers

    Tackles issues #60 and #75.

    APIGatewayV2HTTPResponse expects the Headers to be in the form of Content-Type: application/json or Content-Type: application/json,text-plain.

    Taken from AWS documentation here:

    Request parameter mapping values

    Type | Syntax | Notes --|--|-- Header value | $request.header.name | Header names are case-insensitive. API Gateway combines multiple header values with commas, for example "header1": "value1,value2". Some headers are reserved. To learn more, see Reserved headers.

    #97 tries to fix this issue but is missing some changes and tests to back it up. So I am opening another one.

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by jccguimaraes 5
  • Support for 2.0 payload format

    Support for 2.0 payload format

    Issue #, if available: #60 Description of changes: Adds support for 2.0 payload format. This is basically a copy of what was done for 1.0 payload format.

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by itmeze 5
  • Support V2 requests for Chi

    Support V2 requests for Chi

    Description of changes: Support V2 requests for the Chi framework

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by AlexLast 1
  • Add missing package name to gin example

    Add missing package name to gin example

    Fix example code in README for Gin framework

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by beaspider 0
  • Added request PathParameter to context

    Added request PathParameter to context

    Issue #, if available: #153

    Description of changes:

    Similar to how the stage variables support is implemented, I've added support for accessing path parameters through the request context and header.

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by reecerussell 1
  • Method to access a request's PathParameters

    Method to access a request's PathParameters

    Hey all,

    I've encountered an issue where I need to access the API Gateway request's path parameters. I can see that there are methods to access the request context and stage variables, however, no method to access the path parameters.

    This would be really helpful when it comes to building APIs with route/path parameters, for example: "/items/{itemId}".

    opened by reecerussell 0
  • ⚗️ re-concatenate UserAgents that get split up

    ⚗️ re-concatenate UserAgents that get split up

    This is a fix for #150 - I'm sure it would be better to fix where it splits at the comma in the 1st place, but this at least helps identify the problem

    When going from CloudFront -> Api Gateway -> Lambda my user agent looks like this:

    like Gecko) Chrome/105.0.0.0 Safari/537.36,
    

    While locally I get the full string:

    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
    
    opened by acidjazz 0
Owner
Amazon Web Services - Labs
AWS Labs
Amazon Web Services - Labs
Apis para la administracion de notifiaciones, utilizando servicios como AWS SNS y AWS SQS

notificacion_api Servicio para envío de notificaciónes por difusión en AWS SNS Especificaciones Técnicas Tecnologías Implementadas y Versiones Golang

Universidad Distrital Francisco José de Caldas 0 Jan 7, 2022
Lambda microservice triggered by API Gateway to lookup ip address, domain or hash (md5, sha1, sha256)

lambdaGatewayAPI Lambda microservice triggered by API Gateway to lookup ip address, domain or hash (md5, sha1, sha256) How to deploy Build the lambdaG

null 0 Dec 21, 2021
The wazuh-integratord is a daemon that allows Wazuh to connect to external APIs and alerting tools such as Slack, VirusTotal and PagerDuty.

The wazuh-integratord is a daemon that allows Wazuh to connect to external APIs and alerting tools such as Slack, VirusTotal and PagerDuty.

Admicro 2 Apr 22, 2022
starenv allows populating environmental variables from variety of sources, such as AWS Parameter Store, GPG encrypted files and more, with extreme ease.

starenv (*env) allows populating environmental variables from variety of sources, such as AWS Parameter Store, GPG encrypted files and more, with extr

Mansour Behabadi 6 Nov 25, 2022
Mrrobot - A simple greetings bot for Slack that uses events api and hosted on AWS Lambda

Mr. Robot a greeter bot for your slack community build_docker

Andrew Minkin 1 Aug 21, 2022
Simple CRUD API written in Go, built using AWS SAM tool and using the AWS' infrastructure.

tutor-pet API Simple CRUD API written in Go, built using AWS SAM tool and using the AWS' infrastructure. Macro architecture: Code architecture: Pre-Re

Lucas Ferreira 3 Aug 17, 2022
Lambda stack to turn off and destroy all resources from your personal AWS Account to avoid billing surprises

AWS, Turn off my Account, please Lambda stack to turn off and destroy all resources from your personal AWS Account to avoid billing surprises Resource

Matheus Fidelis 67 Oct 25, 2022
This repository shows how can we use `AWS Lambda` to build serverless applications in golang.

Serverless Api in Go with AWS Lambda Here we are going to use AWS Lambda to build serverless applications in golang. Prerequisites You’ll need an AWS

Datum Brain 0 Nov 3, 2021
Golang AWS SAM Lambda example

Golang AWS SAM Lambda example This example project shows how to use AWS SAM with

Micah Parks 5 Nov 18, 2022
Go-xrayprofile - Selective profiling of AWS Lambda functions

go-xrayprofile AWS X-Ray is handy for understanding the overall performance of y

Aidan Steele 7 May 18, 2022
Http apis with AWS CDK for Go

Http apis with AWS CDK for Go Blog: https://harshq.medium.com/building-apps-with-aws-sdk-for-golang-api-gateway-and-lambda-b254858b1d71 Useful command

Harshana Abeyaratne 1 Jan 4, 2022
A demonstration of the transactional outbox messaging pattern (+ Log Trailing) with Amazon DynamoDB (+ Streams) written in Go.

Transactional Outbox Pattern in Amazon DynamoDB A demonstration of the transactional outbox messaging pattern (+ Log Trailing) with Amazon DynamoDB (+

A. Ruiz 3 Apr 12, 2022
null 2 Feb 7, 2022
Una prueba técnica: Servicio Golang REST API local, sobre Docker, gRPC, AWS Serverless y sobre Kubernetes en AWS EC2

Una prueba técnica: Servicio Golang REST API local, sobre Docker, gRPC, AWS Serverless y sobre Kubernetes en AWS EC2

Emilio del Cañal Calleja 4 May 7, 2022
AWS credential_process utility to assume AWS IAM Roles with Yubikey Touch and Authenticator App TOPT MFA to provide temporary session credentials; With encrypted caching and support for automatic credential refresh.

AWS credential_process utility to assume AWS IAM Roles with Yubikey Touch and Authenticator App TOPT MFA to provide temporary session credentials; With encrypted caching and support for automatic credential refresh.

Ari Palo 18 Oct 27, 2022
Go Client Library for Amazon Product Advertising API

go-amazon-product-advertising-api Go Client Library for Amazon Product Advertising API How to Use go get -u github.com/ngs/go-amazon-product-advertisi

Atsushi NAGASE 54 Sep 27, 2022
Simple no frills AWS S3 Golang Library using REST with V4 Signing (without AWS Go SDK)

simples3 : Simple no frills AWS S3 Library using REST with V4 Signing Overview SimpleS3 is a golang library for uploading and deleting objects on S3 b

Rohan Verma 95 Nov 4, 2022
Integrate AWS EKS Anywhere cluster with AWS Services

This article provides step-by-step instruction on integrating AWS EKS Anywhere with AWS Services so the applications running on customer data center can securely connect with these services.

Hari Ohm Prasath 2 Mar 6, 2022
A package for access aws service using AWS SDK for Golang

goaws ?? A package for access aws service using AWS SDK for Golang Advantage with goaws package Example for get user list IAM with AWS SDK for Golang

Muhammad Ichsanul Fadhil 1 Nov 25, 2021