Giter VIP home page Giter VIP logo

aws-lambda-go-api-proxy's Introduction

AWS Lambda Go API Proxy Build Status

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

Getting started

Install required dependencies.

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

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

Standard library

To use with the standard library, the httpadaptor.New function takes in a http.Handler. The ProxyWithContent method on the httpadapter.HandlerAdapter can then be used as a Lambda handler.

package main

import (
	"io"
	"net/http"

	"github.com/aws/aws-lambda-go/lambda"
	"github.com/awslabs/aws-lambda-go-api-proxy/httpadapter"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "Hello")
	})

	lambda.Start(httpadapter.New(http.DefaultServeMux).ProxyWithContext)
}

Gin

To use with the Gin framework, following the instructions from the Lambda documentation, declare a Handler method for the main package.

Declare a ginadapter.GinLambda object in the global scope, and initialize it in the init function, adding all API methods.

The ProxyWithContext method is then used 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)
}

Fiber

To use with the Fiber framework, following the instructions from the Lambda documentation, declare a Handler method for the main package.

Declare a fiberadapter.FiberLambda object in the global scope, and initialize it in the init function, adding all API methods.

The ProxyWithContext method is then used to translate requests and responses.

// main.go
package main

import (
	"context"
	"log"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	fiberadapter "github.com/awslabs/aws-lambda-go-api-proxy/fiber"
	"github.com/gofiber/fiber/v2"
)

var fiberLambda *fiberadapter.FiberLambda

// init the Fiber Server
func init() {
	log.Printf("Fiber cold start")
	var app *fiber.App
	app = fiber.New()

	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("Hello, World!")
	})

	fiberLambda = fiberadapter.New(app)
}

// Handler will deal with Fiber working with Lambda
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 fiberLambda.ProxyWithContext(ctx, req)
}

func main() {
	// Make the handler available for Remote Procedure Call by AWS Lambda
	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 gateway context, stage variables and lambda runtime variables are automatically populate to the context.

// the methods are available in your instance of the GinLambda
// object and receive the context
apiGwContext := ginLambda.GetAPIGatewayContextFromContext(ctx)
apiGwStageVars := ginLambda.GetStageVarsFromContext(ctx)
runtimeContext := ginLambda.GetRuntimeContextFromContext(ctx)

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


// 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.

aws-lambda-go-api-proxy's People

Contributors

alexlast avatar arentta avatar bhavik1st avatar danielwhite avatar dave-malone avatar dependabot[bot] avatar drakejin avatar hohmannr avatar jancona avatar jslang avatar jt0 avatar k-bailey avatar magnetikonline avatar marvin-w avatar mborromeo avatar minchao avatar mousedownmike avatar nelz9999 avatar nsarychev avatar raeesbhatti avatar raff avatar rymurr avatar sapessi avatar spolischook avatar tanishiking avatar tharun-d avatar uded avatar uji avatar vishal24tuniki avatar zoltanarvai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-lambda-go-api-proxy's Issues

using context.Request.BasicAuth() with cognito Authorizer

Hello is there a way to decrypt the cognito access token as a map?
context.Request.BasicAuth() returns a strings, where all the user attributes are return as a multi line string in the password return var (uname,password, bool).

Or do I have to code something for this ?

Thanks in advance!

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.

Lambda - using gateway 301 error

i had added follow sameple code, zip and upload to aws lambda
but its not work for me...
Any suggestion please?


่žขๅน•ๆˆชๅœ– 2020-09-23 ไธ‹ๅˆ12 48 38

่žขๅน•ๆˆชๅœ– 2020-09-23 ไธ‹ๅˆ12 48 53


import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/apex/gateway"
)

func main() {
	http.HandleFunc("/", hello)
	log.Fatal(gateway.ListenAndServe(":3000", nil))
}

func hello(w http.ResponseWriter, r *http.Request) {
	// example retrieving values from the api gateway proxy request context.
	requestContext, ok := gateway.RequestContext(r.Context())
	if !ok || requestContext.Authorizer["sub"] == nil {
		fmt.Fprint(w, "Hello World from Go")
		return
	}

	userID := requestContext.Authorizer["sub"].(string)
	fmt.Fprintf(w, "Hello %s from Go", userID)
}

Recommendation: Move framework specific adapters out of the package

I think we should move out the adapters into separate repos and keep this repository clean and focusing only on the core. The maturity and capability of this lib should not be determined by the availability and readiness of individual bindings. All this lib should do is the core maintained.

It would be simply easier to maintain the individual adapters.

Generalize adapters

chi.Mux, gin.Engine, gorillamux.Router, http.HandlerFunc and negroni.Negroni all implements the http.Handler interface, and all there adapter files are strikingly similar. All the adapters could probably be replaced with a single adapter which takes that http.Handler interface instead of the concrete implementations.

Which I noticed after opening #17 which adds this to only the handlerfunc package a new httpadapter package. (Which all others could delegate to).

Support QueryStringParameters for tools that have not yet support MultiValueQueryStringParameters

QueryStringParameters support had dropped when this module added support for MultiValueQueryStringParameters to avoid adding same values twice #26 (comment)

However, some tools have not yet supported MultiValueQueryStringParameters (e.g. aws-sam-cli has not yet supported MultiValueQueryStringParameters).

What do you think about support QueryStringParameters (while avoiding the duplicated values)?
Or should we expedite the PR ?

How to set the stripBasePath on a gin instance

I have an API setup with a custom domain and base path mappings. I see there is a stripBasePath field but it is promoted in the ginLambda instance and not exported.

Can we add an example in the readme on how to set stripBasePath on the ginAdapter. Currently unclear how to do it.

Drop Iris

Iris is basically a weird scam of some kind. You should just drop it. It already caused #70 because the developer is always using weird sock puppets and force pushes to make the project look active (why?). Iโ€™m sure heโ€™s going to get a lot of sock puppets to complain, but all the more reason to cut it loose while you can.

Custom host (cont.)

I saw that we made some effort to make the hostname more customizable (relevant issues: #21 and #13). I think we can make it even more flexible by allowing consumer to opt-in the option to use, wait for it, Host header as the hostname.

In normal context, this is a terrible idea as Host header can't be trusted at all. In APIG/Lambda context -- which is what this library is about -- I think it's an acceptable option. The reason being, API Gateway and CloudFront already reject all the requests with irrelevant Host header. And those that hit Lambda are those that we can trust.

Hence, would using incoming Host header as hostname be something we can consider as an option?

fiber adapter cannot pass some specific 'header' to fiber app.

Thanks gofiber team.

Sorry for my poor English.
This issue about PR #69

Bug

My HTTP client(Chrome browser) transfers HTTP packets with a 'Content-Type' header to the AWS API gateway.
But, My fiber application cannot read a 'Content-Type' header when using a lambda fiber adapter.

test code

below code is part of this link

       app.Get("/ping", func(c *fiber.Ctx) error {
		fmt.Println("Step 7------", string(c.Request().Header.Header())) // You can see "application/json" at this codes .
		// but you cannot find "Content-Type" using below method.
		// c.Get(fiber.HeaderContentType, "") print out "" empty string.
		Expect(fiber.MIMEApplicationJSON).To(Equal(c.Get(fiber.HeaderContentType, "")))
		Expect("drakejin").To(Equal(c.Get("MyNameIs", "")))

		log.Println("Handler!!")
		return c.SendString("pong")
	})

	adapter := fiberadaptor.New(app)

	req := events.APIGatewayProxyRequest{
		Path:       "/ping",
		HTTPMethod: "GET",
		Headers: map[string]string{
			"Content-Type": fiber.MIMEApplicationJSON,
			"MyNameIs":     "drakejin",
		},
	}

Plz, Check these codes fiberlambda_test.go, adapter.go. It explains what happened to lambda fiber adapter codes.
). It explains what happened to lambda fiber adapter codes.

Root cause

I think this root cause is below this line. It didn't consider about fasttext's header. fasttext/~~/header.go

	for key, val := range r.Header {
		for _, v := range val {
			req.Header.Add(key, v) // <===== this line
		}
	}

I don't have any idea to fix this problem. This below code is my best. sorry, It didn't help

	for key, val := range r.Header {
		for _, v := range val {
			req.Header.Add(key, v)
			if key == fiber.HeaderContentType {
			       req.Header.SetContentType(v) // this solution is wack but, It's my best. (i don't know fasttext 
			}
		}
	}

help @Fenny @kiyonlin

502 Bad Gateway error because Headers field is nil

I get 502 Bad Gateway response from AWS LB using the exact source code from the README with the latest release v0.8.1.

This is due to a recent change in #73 which results in Headers being set to nil on the proxy response. You can work around this by adding Headers to the proxied response.

Lambda output and HTTP response using the code from the README:

{
  "statusCode": 200,
  "headers": null,
  "multiValueHeaders": {
    "Content-Type": [
      "application/json; charset=utf-8"
    ]
  },
  "body": "{\"message\":\"pong\"}"
}
$ curl http://<removed>.elb.amazonaws.com/ping
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
</body>
</html>

My workaround:

func Handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	// If no name is provided in the HTTP request body, throw an error
	resp, err := ginLambda.ProxyWithContext(ctx, req)
	headers := make(map[string]string)
	headers["Content-Type"] = "application/json"
	resp.Headers = headers
	return resp, err
}

Lambda output and HTTP response with this workaround:

{
  "statusCode": 200,
  "headers": {
    "Content-Type": "application/json"
  },
  "multiValueHeaders": {
    "Content-Type": [
      "application/json; charset=utf-8"
    ]
  },
  "body": "{\"message\":\"pong\"}"
}
$ curl -i http://<removed>.elb.amazonaws.com/ping
HTTP/1.1 200 OK
Server: awselb/2.0
Date: Thu, 08 Oct 2020 18:59:03 GMT
Content-Type: application/json
Content-Length: 18
Connection: keep-alive

{"message":"pong"}

Enabling CORS

How may I enable CORS for this setup? Please help

ProxyWithContext function doesn't work using custom domain

I want to ask about when setting a custom domain and base path on api gateway.

I set a custom domain and base path on api gateway.
(https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)
In this case, events.APIGatewayProxyRequest returns the Path including base path.

For example (base path => 'basepath', resource path => api/v1)

access via api gateway URL:
APIGatewayProxyRequest.Path => api/v1

access via custom domain:
APIGatewayProxyRequest.Path => basepath/api/v1

When custom domain access, APIGatewayProxyRequest.Path is different.
And in this case, I called ProxyWithContext function, it returned an error below. (using api gateway url (https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/), it's work.)

NEXTGEN_NotFoundHttpException, No route found for \"GET /basepath/api/v1\"

HTTP API's collate headers and multivalueheaders for duplicate responses

So, here's a doozy bug that I encountered using the Gateway HTTP API (the new version) and the events returned from this proxy, that results in the duplication of headers. The process is this:

1. I attach a location header to my response

rw.Header().Set("Location", location)

2. The following event is produced by the go-api-proxy

{
    "statusCode": 201,
    "headers": {
        "Location": "my-location"
    },
    "multiValueHeaders": {
        "Location": [
            "my-location"
        ]
    },
    "body": ""
}

3. Duplicated headers received by the client

So far so good, right? Well, it turns out that the HTTP response that the client receives looks like this:

apigw-requestid: R4j5hhzBvHcEJ4w=
content-length: 0
date: Wed, 26 Aug 2020 15:31:10 GMT
location: my-location
location: my-location
status: 201

A bit more investigation, and I discovered that the HTTP API Gateway event translation merges the responses from both 'headers' and 'multiValueHeaders', creating the above multi-header response. Now, the multiple location headers are, strictly speaking, valid HTTP. However, according to the docs:

If you specify values for both headers and multiValueHeaders, API Gateway merges them into a single list. If the same key-value pair is specified in both, only the values from multiValueHeaders will appear in the merged list.

Workaround

The simplest workaround is to add an event interceptor in golang that deletes either of the two header blocks before returning it. Or, well, merge #73

CVE-2020-28483

Used version of github.com/gin-gonic/gin v1.6.3 is vulnerable to CVE-2020-28483.

name: Inconsistent Interpretation of HTTP Requests (HTTP Request Smuggling)
message: Inconsistent Interpretation of HTTP Requests (HTTP Request Smuggling) in github.com/gin-gonic/gin
description: When gin is exposed directly to the internet, a client's IP can be spoofed by setting the X-Forwarded-For header.

solution: Upgrade to version 1.7.0 or above.

CVE-2020-28483: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-28483

Support compression/GZIP on ALB

Hello,

Is there anyway to support GZIP while using the ALB? I know the API GW supports compression, however, I'm not using that.

I've seen that there isn't "full" support for ALB right now, but it's working just fine for me.

Any tips would be appreciated, thanks!

ProxyResponseWriter.Write is a little too "naive"

This implementation seems to imply the handler will do only one Write to complete the request, that is not true (or not documented anywhere):

func (r *ProxyResponseWriter) Write(body []byte) (int, error) {
	r.body = body
        ...

Maybe changing ProxyResponseWriter.body to a bytes.Buffer would be a better implementation.

Use go mod for dependency management

govendor has been archived and deprecated by it's author and they suggest using go mod to manage dependencies.
I'm trying to contribute to this project and I need to update a dependency but I'm unable to do so using govendor. Please use go mod for dependency management!

Custom headers not being returned by sam local

Hi there - I am trying to add custom headers to a api response coming from gin proxy but these seem to be ignored completely by sam local.

prob. more of a sam local - issue so opened for any info

Are there any examples of doing so ?

regards

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?

Include Request ID from APIGatewayProxyRequestContext

Hi,

According the function EventToRequest, it only processes the field req.RequestContext.DomainName, but ignored the rest fields of req.RequestContext which is APIGatewayProxyRequestContext, could we include the other fields such as RequestID which is the original request ID from API Gateway ? Thanks in advance

Tag latest release

Hello! Could you please tag the repo with an updated version number when you're ready? I'd love to take advantage of the echo lambda handler, but go get won't import the echo handler unless it's in a tagged release. Thank you!

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.

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?

Is it possible to use it with X-Ray?

I have the following setup.

  • Lambda handler:
package main

import (
	"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/maslick/api-less/src"
)

type LambdaController struct {
	src.RestController
}

func (ctrl *LambdaController) LambdaHandler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	router := ctrl.InitRouter()
	return ginadapter.New(router).ProxyWithContext(ctx, req)
}

func main() {
	service := &Service{Repo: &Repo{config()}}
	controller := RestController{Service: service}
	ctrl := LambdaController{controller}
	lambda.Start(ctrl.LambdaHandler)
}
  • Gin REST controller
import (
	"github.com/gin-gonic/gin"
)

type RestController struct {
	Service IService
}

func (api *RestController) InitRouter() *gin.Engine {
	router := gin.New()
	public := router.Group("/")
	public.GET("/users", api.Service.findAllUsers)
	return router
}

func (api *RestController) findAllUsers(c *gin.Context) {
	employees, err := api.Service.findAllUsers(c.Copy())
	if err != nil {
		c.String(500, err.Error())
		return
	}
	c.JSON(http.StatusOK, response)
}
  • Service layer
import (
	"context"
)

type IService interface {
	FindAllUsers(ctx context.Context) ([]User, error)
}

type Service struct {
	Repo   IRepo
}

func (s *Service) findAllUsers(ctx context.Context) ([]User, error) {
	return s.Repo.FindAllUsers(ctx)
}
  • Repository layer
import (
	"context"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
	"github.com/aws/aws-xray-sdk-go/xray"
)

type IRepo interface {
	FindAllUsers(ctx context.Context) ([]User, error)
}

type Repo struct {
	db *dynamodb.DynamoDB
}

func config() *dynamodb.DynamoDB {
	region := GetEnv("REGION", "eu-central-1")
	config := &aws.Config{
		Region: aws.String(region),
	}

	sess := session.Must(session.NewSession(config))
	svc := dynamodb.New(sess)
	xray.AWS(svc.Client)
	return svc
}

func (r *Repo) FindAllUsers(ctx context.Context) ([]User, error) {
	var users []User
	input := &dynamodb.ScanInput{
		TableName: &tableName,
	}
	result, _ := r.db.ScanWithContext(ctx, input)

	for _, i := range result.Items {
		item := User{}
		_ = dynamodbattribute.UnmarshalMap(i, &item)
		users = append(users, item)
	}

	return users, nil
}

Is it possible to use XRay with aws-lambda-go-api-proxy? I get the following error in Cloudwatch:

2020-07-05T12:28:20Z [ERROR] Suppressing AWS X-Ray context missing panic: failed to begin subsegment named 'dynamodb': segment cannot be found.
2020-07-05T12:28:20Z [ERROR] Suppressing AWS X-Ray context missing panic: failed to begin subsegment named 'attempt': segment cannot be found.
2020-07-05T12:28:20Z [ERROR] Suppressing AWS X-Ray context missing panic: failed to begin subsegment named 'unmarshal': segment cannot be found.

Any ideas? Thanks in advance!

sam local start-api got the error message: Invalid API Gateway Response

Hello,
I follow the sample to develop my lambda function and it's working well, but today I got some error message and try the sample again got the same error message.

Invoking main (go1.x)
Decompressing /private/tmp/aws-lambda-go-api-proxy/sample/main.zip

Fetching lambci/lambda:go1.x Docker container image......
Mounting /private/var/folders/m0/_9179l9507jf8r61173wrvg40000gn/T/tmpbthat67r as /var/task:ro,delegated inside runtime container
START RequestId: 8e9f234a-b0e8-1746-4601-ec5a9ce55d2c Version: $LATEST
END RequestId: 8e9f234a-b0e8-1746-4601-ec5a9ce55d2c
REPORT RequestId: 8e9f234a-b0e8-1746-4601-ec5a9ce55d2c	Init Duration: 91.11 ms	Duration: 2.25 ms	Billed Duration: 100 ms	Memory Size: 128 MB	Max Memory Used: 14 MB	
Invalid API Gateway Response Keys: {'errorType', 'errorMessage'} in {'errorType': 'exitError', 'errorMessage': 'RequestId: 23a9762d-bfdc-13ab-f40b-ad1433273dc5 Error: fork/exec /var/task/main: exec format error'}
Function returned an invalid response (must include one of: body, headers, multiValueHeaders or statusCode in the response object). Response received: {"errorType":"exitError","errorMessage":"RequestId: 23a9762d-bfdc-13ab-f40b-ad1433273dc5 Error: fork/exec /var/task/main: exec format error"}
2019-12-23 17:17:49 127.0.0.1 - - [23/Dec/2019 17:17:49] "GET /pets/1 HTTP/1.1" 502 -

I have no idea what happened, it's working before today.

Build process with Glide

Moving this from a comment on #9 by @dave-malone to a new issue

instead of the Makefile, would you be open to other options for building this project? For instance, using Glide we can run all tests with simpler commands:

go test ./... $(glide novendor) --cover

Tag a release

Can you tag a release? I don't like pinning to shas.

Override DefaultServerAddress from APIGatewayProxyRequest

I know this has been looked at previously in #13 and associated PR, but with API GW returning the host, is there any reason not to default to the host as passed in the APIGatewayProxyRequest instead of the DefaultServerAddress? I can understand https://aws-serverless-go-api.com being a fallback if no host is passed from API GW, but defaulting to the actual host would get us closer to the integrity of the original http request.

Failed to build, package module need to be updated

unable to build my app. Following error is popingup

github.com/awslabs/[email protected] requires
github.com/gorilla/[email protected]: invalid version: git fetch -f origin refs/heads/:refs/heads/ refs/tags/:refs/tags/ in C:\Users\Ankit Patial\go\pkg\mod\cache\vcs\ebce69d65fcbb10d46c06b9a96d0b75cbef4f6fe72077ff7900bc6194bb0d703: exit status 128:
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Seems like package module need to be updated

Gin/mux support for aws alb

Gin/mux doesnt work with aws alb. With reinvent 2018, lambda can we invoked from aws alb. Do you have plan to fix/support this?

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!

ProxyWithContext function does not support APIGatewayV2HTTPRequest

Problem

related to issue aws/aws-lambda-go#345 (comment)

Proxy and ProxyWithContext functions do not support APIGatewayV2HTTPRequest as they only supports APIGatewayProxyRequest

func (g *GinLambda) Proxy(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	...
}

func (g *GinLambda) ProxyWithContext(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
...
}

Feature request

Please add a version of the functions that supports APIGatewayV2HTTPRequest e.g.

func (g *GinLambda) Proxy(req events.APIGatewayV2HTTPRequest) (events.APIGatewayProxyResponse, error) {
	...
}

func (g *GinLambda) ProxyWithContext(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayProxyResponse, error) {
...
}

Detect Content Type on Write

It would be nice if this detected content type on Write (just as the standard library does) rather than leave it unset.

I would be willing to work on this.

About performance

Hi,
Just to be sure, Is there any performance impact (regarding container reusing or anything else) if I do this:

// ...

func main() {
    // my initialization here

    lambda.Start(Handler)
}

instead of this

func init() {
    // my initialization here
}

// ...

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

?

GetAPIGatewayContext doesn't work when using `ProxyWithContext`

I have code that looks something like:

var (
	muxLambda *gorillamux.GorillaMuxAdapter
)

func main() {
	router := mux.NewRouter()

         // ...some routes are defined here...

	muxLambda = gorillamux.New(router)

	lambda.Start(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
		return muxLambda.ProxyWithContext(ctx, req)
	})
}

func MyHandler(w http.ResponseWriter, r *http.Request) {
	reqCtx, err := muxLambda.GetAPIGatewayContext(r)
	// Do stuff with reqCtx
}

The call to muxLambda.GetAPIGatewayContext(r) is returning an error:

"No context header in request"

I'm not super familiar with the inner workings of this repo, but it looks like the GetAPIGatewayContext is expecting a custom "X-GoLambdaProxy-ApiGw-Context" header to be set elsewhere in the code, before my route handler is called. It looks like the Proxy() method results in the header getting set (by calling ProxyEventToHTTPRequest, which calls addToHeader), but the ProxyWithContext method doesn't follow this same code path.

Is this a bug in the ProxyWithContext method, or maybe I'm misunderstanding how this is supposed be used?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.