Drop-in replacement for Go net/http when running in AWS Lambda & API Gateway

Overview

Package gateway provides a drop-in replacement for net/http's ListenAndServe for use in AWS Lambda & API Gateway, simply swap it out for gateway.ListenAndServe. Extracted from Up which provides additional middleware features and operational functionality.

There are two versions of this library, version 1.x supports AWS API Gateway 1.0 events used by the original REST APIs, and 2.x which supports 2.0 events used by the HTTP APIs. For more information on the options read Choosing between HTTP APIs and REST APIs on the AWS documentation website.

Installation

To install version 1.x for REST APIs.

go get github.com/apex/gateway

To install version 2.x for HTTP APIs.

go get github.com/apex/gateway/v2

Example

package main

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)
}

GoDoc

Comments
  • Add support for 2.0 apigw request/response

    Add support for 2.0 apigw request/response

    • This adds a new v2 module in a subfolder which support for 2.0 api gateway request/response
    • Ensure tests use canonical format used in 1.14
    • Upgrade dependencies
    • Use the Handler interface to make the packages more extensible
    opened by wolfeidau 17
  • Not compatible with gateway v2

    Not compatible with gateway v2

    This code works just fine.

    package main
    
    import (
     "context"
     "fmt"
    
     "github.com/aws/aws-lambda-go/lambda"
    )
    
    func HandleRequest(ctx context.Context) (string, error) {
      return fmt.Sprintf("Hello!"), nil
    }
    
    func main() {
      lambda.Start(HandleRequest)
    }
    

    When I replace it with

    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    
    	"github.com/apex/gateway"
    )
    
    func main() {
    
    	http.HandleFunc("/", hello)
    
    	log.Fatal(gateway.ListenAndServe(":3000", nil))
    	// log.Fatal(http.ListenAndServe(":3000", nil))
    }
    
    func hello(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprintf(w, "Hello!")
    }
    

    I am getting:

    curl https://dqt4t5gx.execute-api.eu-central-1.amazonaws.com/
    <a href="//dqt4t5gx.execute-api.eu-central-1.amazonaws.com/">Moved Permanently</a>.
    

    Could this be because I am using the aws_apigatewayv2_api resource? Or any other pointers?

    opened by tcurdt 10
  • add support for `APIGatewayProxyRequestContext`

    add support for `APIGatewayProxyRequestContext`

    This would be useful to get access to more values from the context, for instance when using api gateway authorizers.

    Another option would be to json serialize the context and pass it as a header. I'm not sure what would be preferable?

    opened by olivoil 5
  • Memory usage

    Memory usage

    With gateway a single Lambda function might handle many API Gateway requests, what happens when it exceeds the allocated memory?

    It seems like AWS Lambda is somewhat flexible with the amount of memory the function may use, and I assume it will then start another if the account has concurrency available?

    opened by mozey 3
  • Actually sniff content-type on write

    Actually sniff content-type on write

    It would be nice if the library would sniff the content type if it's not already explicitly set rather than just using text/plain. I would be willing to work on this if you want.

    opened by haydenwoodhead 2
  • Add stage path to request path if api gateway host

    Add stage path to request path if api gateway host

    url: https://1234567890.execute-api.us-east-1.amazonaws.com/prod/pets expected path: /prod/pets actual path: /pets

    This will add the stage path part to the request url path if the host is an aws api gateway host.

    opened by dabio 2
  • fix(Response) Fix for autodetect text mime types.

    fix(Response) Fix for autodetect text mime types.

    The original code returned base64 content when https://github.com/gin-gonic/gin provided the following mime type application/json; charset=utf-8 for JSON.

    This fix works based on my testing, interested to hear your thoughts on using the inbuilt mime package for parsing.

    • Changed matching to allow for trailing encoding.
    • Added a test case for the updated function.
    opened by wolfeidau 2
  • Remove unnecessary import in README

    Remove unnecessary import in README

    Hey, the import of the aws-lambda-go is

    a) Broken. Because it's missing a /lambda at the end and b) Unnecessary for the example and go build will complain.

    So I removed it ;) This also 'fixes' the problem in #22

    Best regards, Felix

    Priority: Normal 
    opened by fleaz 1
  • Is it possible to include assets in the binary?

    Is it possible to include assets in the binary?

    Hello,

    I've only just come across this library and I think it's great! I was trying to figure out how I could build some small generic tools that run directly on lambda for mostly house keeping tasks and I think this will do the trick.

    I was wondering though, is it possible to use something like packr to include (a very small amount) of files within my go binary?

    I've literally just done a drop in replacement for the gin app I was working on and it's deployed fine to lambda and serves my gin site but I was hoping to be able to include a couple of css, js files with this rather than hosting those in s3 or elsewhere.

    opened by dre2004 1
  • Reordering query parameters.

    Reordering query parameters.

    Ideally nothing out there should rely on query parameter ordering, but lots of things do unfortunately, so the request that is build and passed in to the handler should have the original rawquery set.

    opened by yonderblue 1
  • Pass-through incoming ctx to Request

    Pass-through incoming ctx to Request

    Hi there!

    This fixes what I think is a bug in passing-through the incoming ctx value to the created Request. Without this fix, the incoming ctx is lost, so for instance the values that are set by https://github.com/aws/aws-lambda-go are lost and you can't use lambdacontext.FromContext(r.Context()) to get the lambda context info back.

    opened by dstrelau 1
  • API gateway resource does not pass into handler

    API gateway resource does not pass into handler

    I used this dependency in my go project for lambda function and api gateway. The api gateway do invoke the lambda function, however the api call returns 404 page not found error. And in the log, the path is / instead of the/resource. Do you have any suggestions?

    opened by chichunhua 0
  • Treat JSON API responses as the text they are

    Treat JSON API responses as the text they are

    The content-type "application/vnd.api/json" is a text based JSON response type. Lets treat it as such.

    Refernce: https://jsonapi.org/format/

    opened by aolley 1
  • This project could use some love...

    This project could use some love...

    I'm looking around for a lambda adapter to use with go-chi/chi...Apex Gateway looks neat, but...unloved (trying to avoid calling this "abandoned").

    • Issues left open when they could be closed
    • Unanswered questions in issues
    • PRs sitting open for months

    I know one of the maintainers left $employer, but is this of interest to Apex to maintain, or maybe add some outside maintainers? Is there a popular fork of this, perhaps that I'm not aware of?

    awslabs/aws-lambda-go-api-proxy is equally un-loved (including security vulns), davyzhang/agw is interesting but lacking stars. Is there some other well-maintained way that people are integrating lambda and go http routers?

    opened by jlk 3
  • Fix duplicate set-cookie headers

    Fix duplicate set-cookie headers

    Currently, this will result in 2 set-cookie headers. One in Headers and one in Cookies.

    	http.SetCookie(w, &http.Cookie{
    		Name:  "foo",
    		Value: "bar",
    	})
    

    Without this fix, the included test fails on assert.Equal(t, 1, len(e.Headers)) (has 2, Content-Type + Set-Cookie)

    Also @wolfeidau @tj the tests are passing, though like in https://github.com/apex/gateway/pull/39, I'm guessing this will fail with AWS Build/Semaphore - are these build processes broken? Maybe we can just disable them and just use Actions to run the tests.

    opened by jpillora 1
  • Maximum (50) redirects followed

    Maximum (50) redirects followed

    I switched my API to use the cheaper HttpApi type from the REST protocol type https://s.natalian.org/2021-04-19/httpApi.txt which also has JWT Authorizer type support and now I get a redirect loop.

    I guess it's something to do with the different interface PayloadFormatVersion 2.0?

    opened by kaihendry 2
Owner
Apex
Building beautiful solutions
Apex
protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript clients that connect the web frontend and golang backend fronted by grpc-gateway.

protoc-gen-grpc-gateway-ts protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript

gRPC Ecosystem 94 Dec 19, 2022
Internet connectivity for your VPC-attached Lambda functions without a NAT Gateway

lambdaeip Internet connectivity for your VPC-attached Lambda functions without a NAT Gateway Background I occasionally have serverless applications th

Glass Echidna 23 Nov 9, 2022
The Durudex gateway combines all durudex services so that it can be used through a single gateway.

The Durudex gateway combines all durudex services so that it can be used through a single gateway.

null 12 Dec 13, 2022
Grpc-gateway-map-null - gRPC Gateway test using nullable values in map

Demonstrate gRPC gateway behavior with nullable values in maps Using grpc-gatewa

null 1 Jan 6, 2022
Go package to simulate bandwidth, latency and packet loss for net.PacketConn and net.Conn interfaces

lossy Go package to simulate bandwidth, latency and packet loss for net.PacketConn and net.Conn interfaces. Its main usage is to test robustness of ap

Cevat Barış Yılmaz 313 Oct 14, 2022
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

fasthttp Fast HTTP implementation for Go. Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than

Aliaksandr Valialkin 18.9k Jan 5, 2023
Simple GUI to convert Charles headers to golang's default http client (net/http)

Charles-to-Go Simple GUI to convert Charles headers to golang's default http client (net/http) Usage Compile code to a binary, go build -ldflags -H=wi

null 0 Dec 14, 2021
No-frills all-in-one HTTP API gateway

SX: a minimal, declarative API gateway WARNING: not production ready. Use at your own risk! Need something better? Check out nginx, Caddy or Envoy SX

Giorgio Pellero 1 Dec 18, 2021
Go-http-sleep: Delayed response http server, useful for testing various timeout issue for application running behind proxy

delayed response http server, useful for testing various timeout issue for application running behind proxy

guessi 0 Jan 22, 2022
Super fault-tolerant gateway for HTTP clusters, written in Go. White paper for reference - https://github.com/gptankit/serviceq-paper

ServiceQ ServiceQ is a fault-tolerant gateway for HTTP clusters. It employs probabilistic routing to distribute load during partial cluster shutdown (

Ankit Gupta 66 Jul 16, 2022
Fork of Go stdlib's net/http that works with alternative TLS libraries like refraction-networking/utls.

github.com/ooni/oohttp This repository contains a fork of Go's standard library net/http package including patches to allow using this HTTP code with

Open Observatory of Network Interference (OONI) 30 Sep 29, 2022
A Discord ratelimiter for net/http

A Discord ratelimiter intended to be used with net/http clients using time/x/rate.

null 0 Nov 6, 2021
go stomp server base on net/http

stompserver go stomp server base on "net/http" base on "net/http" and "golang.org/x/net/websocket" so use one port, you can be WebServer or StompServe

0xAAFF 1 Sep 22, 2022
Lux - A web library collection based on net/http

Lux - A web library collection based on net/http

serve-it-yourself 18 Jan 7, 2023
A Realtime API Gateway used with NATS to build REST, real time, and RPC APIs, where all your clients are synchronized seamlessly.

Realtime API Gateway Synchronize Your Clients Visit Resgate.io for guides, live demos, and resources. Resgate is a Go project implementing a realtime

Resgate.io - Synchronize Your Clients 609 Dec 31, 2022
Crank4go API Gateway Brief Introduction It is a Golang implementation of Crank4j

Crank4go API Gateway Brief Introduction It is a Golang implementation of Crank4j, which derived from Cranker. the follow introduction is quoted from t

null 126 Dec 23, 2022
Podbit is a replacement for newsboat's standard podboat tool for listening to podcasts.

Podbit - Podboat Improved Podbit is a replacement for newsboat's standard podboat tool for listening to podcasts. It is minimal, performant and abides

Ethan Marshall 11 Dec 8, 2022
A minimal IPFS replacement for P2P IPLD apps

IPFS-Nucleus IPFS-Nucleus is a minimal block daemon for IPLD based services. You could call it an IPLDaemon. It implements the following http api call

Peergos 29 Jan 4, 2023