algnhsa

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 28, 2023 License: Apache-2.0 Imports: 14 Imported by: 0

README

algnhsa GoDoc Build Status

algnhsa is an AWS Lambda Go net/http server adapter.

algnhsa enables running Go web applications on AWS Lambda and API Gateway or ALB without changing the existing HTTP handlers:

package main

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/acoover/algnhsa"
)

func addHandler(w http.ResponseWriter, r *http.Request) {
	f, _ := strconv.Atoi(r.FormValue("first"))
	s, _ := strconv.Atoi(r.FormValue("second"))
	w.Header().Set("X-Hi", "foo")
	fmt.Fprintf(w, "%d", f+s)
}

func contextHandler(w http.ResponseWriter, r *http.Request) {
	lambdaEvent, ok := algnhsa.APIGatewayV2RequestFromContext(r.Context())
	if ok {
		fmt.Fprint(w, lambdaEvent.RequestContext.AccountID)
	}
}

func main() {
	http.HandleFunc("/add", addHandler)
	http.HandleFunc("/context", contextHandler)
	algnhsa.ListenAndServe(http.DefaultServeMux, nil)
}

Plug in a third-party web framework

Gin
package main

import (
	"net/http"

	"github.com/acoover/algnhsa"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "hi",
		})
	})
	algnhsa.ListenAndServe(r, nil)
}
echo
package main

import (
	"net/http"

	"github.com/acoover/algnhsa"
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "hi")
	})
	algnhsa.ListenAndServe(e, nil)
}
chi
package main

import (
	"net/http"

	"github.com/acoover/algnhsa"
	"github.com/go-chi/chi"
)

func main() {
	r := chi.NewRouter()
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hi"))
	})
	algnhsa.ListenAndServe(r, nil)
}
Fiber
package main

import (
	"github.com/acoover/algnhsa"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/adaptor"
)

func main() {
	app := fiber.New()
	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("Hello, World!")
	})
	algnhsa.ListenAndServe(adaptor.FiberApp(app), nil)
}

Deployment

First, build your Go application for Linux and zip it:

GOOS=linux GOARCH=amd64 go build -tags lambda.norpc -o bootstrap
zip function.zip bootstrap

When creating a new function, choose the "Provide your own bootstrap on Amazon Linux 2" runtime or "Custom runtime on Amazon Linux 2" when modifying an existing function. Make sure to use bootstrap as the executable name and as the handler name in AWS.

AWS provides plenty of ways to expose a Lambda function to the internet.

Lambda Function URL

This is the easier way to deploy your Lambda function as an HTTP endpoint. It only requires going to the "Function URL" section of the Lambda function configuration and clicking "Configure Function URL".

API Gateway
HTTP API
  1. Create a new HTTP API.

  2. Configure a catch-all $default route.

REST API
  1. Create a new REST API.

  2. In the "Resources" section create a new ANY method to handle requests to / (check "Use Lambda Proxy Integration").

  3. Add a catch-all {proxy+} resource to handle requests to every other path (check "Configure as proxy resource").

ALB
  1. Create a new ALB and point it to your Lambda function.

  2. In the target group settings in the "Attributes" section enable "Multi value headers".

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ALBRequestFromContext

func ALBRequestFromContext(ctx context.Context) (events.ALBTargetGroupRequest, bool)

ALBRequestFromContext extracts the ALBTargetGroupRequest event from ctx.

func APIGatewayV1RequestFromContext

func APIGatewayV1RequestFromContext(ctx context.Context) (events.APIGatewayProxyRequest, bool)

APIGatewayV1RequestFromContext extracts the APIGatewayProxyRequest event from ctx.

func APIGatewayV2RequestFromContext

func APIGatewayV2RequestFromContext(ctx context.Context) (events.APIGatewayV2HTTPRequest, bool)

APIGatewayV2RequestFromContext extracts the APIGatewayV2HTTPRequest event from ctx.

func ListenAndServe

func ListenAndServe(handler http.Handler, opts *Options)

ListenAndServe starts the AWS Lambda runtime (aws-lambda-go lambda.Start) with a given handler.

func New

func New(handler http.Handler, opts *Options) lambda.Handler

New returns a new lambda handler for the given http.Handler. It is up to the caller of New to run lamdba.Start(handler) with the returned handler.

func RequestDebugDumpHandler

func RequestDebugDumpHandler(w http.ResponseWriter, r *http.Request)

RequestDebugDumpHandler is an HTTP handler that returns JSON encoded RequestDebugDump.

Types

type Options

type Options struct {
	// RequestType sets the expected request type.
	// By default, algnhsa deduces the request type from the lambda function payload.
	RequestType RequestType

	// BinaryContentTypes sets content types that should be treated as binary types.
	// The "*/* value makes algnhsa treat any content type as binary.
	BinaryContentTypes []string

	// Use API Gateway PathParameters["proxy"] when constructing the request url.
	// Strips the base path mapping when using a custom domain with API Gateway.
	UseProxyPath bool

	// DebugLog enables printing request and response objects to stdout.
	DebugLog bool
	// contains filtered or unexported fields
}

Options holds the optional parameters.

type RequestDebugDump

type RequestDebugDump struct {
	Method string
	URL    struct {
		Path    string
		RawPath string
	}
	RequestURI          string
	Host                string
	RemoteAddr          string
	Header              map[string][]string
	Form                map[string][]string
	Body                string
	APIGatewayV1Request *events.APIGatewayProxyRequest  `json:",omitempty"`
	APIGatewayV2Request *events.APIGatewayV2HTTPRequest `json:",omitempty"`
	ALBRequest          *events.ALBTargetGroupRequest   `json:",omitempty"`
}

RequestDebugDump is a dump of the HTTP request including the original Lambda event.

func NewRequestDebugDump

func NewRequestDebugDump(r *http.Request) (*RequestDebugDump, error)

NewRequestDebugDump creates a new RequestDebugDump from an HTTP request.

type RequestType

type RequestType int
const (
	RequestTypeAuto RequestType = iota
	RequestTypeAPIGatewayV1
	RequestTypeAPIGatewayV2
	RequestTypeALB
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL