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

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

Owner
Apex
Building beautiful solutions
Apex
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
  • 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?

  • 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?

  • 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?

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

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

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

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

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

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

  • 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?

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

  • 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?

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

  • 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?

Zero downtime restarts for go servers (Drop in replacement for http.ListenAndServe)

endless Zero downtime restarts for golang HTTP and HTTPS servers. (for golang 1.3+) Inspiration & Credits Well... it's what you want right - no need t

Dec 29, 2022
Internet connectivity for your VPC-attached Lambda functions without a NAT Gateway
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

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.

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

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

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

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

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

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

Jan 22, 2022
Super fault-tolerant gateway for HTTP clusters, written in Go. White paper for reference - https://github.com/gptankit/serviceq-paper
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 (

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

Sep 29, 2022
A Discord ratelimiter for net/http

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

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

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

Lux - A web library collection based on net/http

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

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

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

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

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

Jan 4, 2023