lambdahttp

package module
v0.0.0-...-a6ffd45 Latest Latest
Warning

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

Go to latest
Published: May 1, 2025 License: Apache-2.0 Imports: 12 Imported by: 0

README

lambdahttp

Go Reference Test Go Report Card

Run standard Go HTTP handlers in AWS Lambda with automatic integration for API Gateway, ALB, and EventBridge.

Overview

This package allows you to run any standard Go http.Handler in AWS Lambda without modification. It automatically detects and handles requests from:

  • API Gateway (v1 and v2)
  • Application Load Balancer (ALB)
  • EventBridge
  • Lambda Function URLs

The main benefits are:

  • Low-Cost Migration: Write your HTTP handlers using standard Go patterns and libraries, then deploy them to AWS Lambda without changing your code
  • Cloud Flexibility: Easily switch between running your application on traditional servers and AWS Lambda without code changes
  • Future-Proof: If you decide to move away from Lambda in the future, your code remains standard and portable

Features

  • 🔄 Use standard http.Handler interface
  • 🔍 Automatic detection of AWS integration type
  • 🌐 Support for multiple AWS services:
    • API Gateway v1
    • API Gateway v2
    • Application Load Balancer
    • EventBridge
    • Lambda Function URLs
  • 📝 Preserves HTTP headers, query parameters, and body

Installation

go get github.com/tjamet/lambdahttp

Quick Start

Here's a simple example of how to use the package:

package main

import (
    "net/http"
    "github.com/tjamet/lambdahttp"
)

func main() {
    // Create your HTTP handler as usual
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`{"message": "Hello from Lambda!"}`))
    })

    // Start the Lambda handler
    serverless.StartLambdaHandler(mux)
}

Advanced Usage

Custom Handler

If you need more control over the Lambda function, you can use NewAWSLambdaHTTPHandler:

package main

import (
    "context"
    "net/http"
    "github.com/tjamet/lambdahttp"
)

func main() {
    handler := serverless.NewAWSLambdaHTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Access the original Lambda request if needed
        originalRequest := serverless.GetOriginalRequest(r)
        
        // Get the integration type
        integrationType := serverless.GetIntegrationType(r)
        
        // Your handler logic here
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`{"message": "Hello!"}`))
    }))

    lambda.Start(handler)
}
Integration Types

The package automatically detects the following integration types:

  • IntegrationTypeAPIGWv1: API Gateway REST API (v1)
  • IntegrationTypeAPIGWv2: API Gateway HTTP API (v2), EventBridge, and Lambda Function URLs
  • IntegrationTypeALB: Application Load Balancer

AWS Service Configuration

API Gateway

For API Gateway, you can use either REST API (v1) or HTTP API (v2). The package will automatically detect the version and handle the request appropriately.

Application Load Balancer

When using an ALB trigger, make sure your target group protocol is set to HTTP.

EventBridge

The package handles EventBridge events by converting them to HTTP requests. The request will be sent as a POST request to the handler.

Lambda Function URLs

Function URLs are automatically detected and handled as API Gateway v2 requests.

Infrastructure as Code Example

For a complete example of how to wire all these integrations together, check out our Terraform module example. This module helps:

  • Setting up Lambda functions with this package
  • Configuring API Gateway integrations (v1 and v2)
  • Setting up ALB targets
  • Configuring EventBridge rules
  • Managing Lambda Function URLs
  • Handling permissions and IAM roles

Contributing

Contributions are welcome! Please feel free to submit an Issue or a Pull Request.

License

[Apache - 2.0] - See LICENSE file for details.

Documentation

Overview

Package lambdahttp provides functionality to run standard Go HTTP handlers in AWS Lambda with automatic integration for various AWS services like API Gateway, ALB, and EventBridge.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetOriginalRequest

func GetOriginalRequest(httpRequest *http.Request) map[string]interface{}

GetOriginalRequest retrieves the original Lambda request from the HTTP request context. Returns nil if no original request is found in the context.

func NewAWSLambdaHTTPHandler

func NewAWSLambdaHTTPHandler(h http.Handler) func(context.Context, LambdaRequest) (Response, error)

NewAWSLambdaHTTPHandler creates a new AWS Lambda handler that can be used to handle HTTP requests It takes an http.Handler and returns a function that can be used as a Lambda handler The handler will automatically detect the api gateway version and build the request accordingly It also handles the case where the request is coming from an ALB

Supported integration types: - APIGWv1: API Gateway v1 - APIGWv2: API Gateway v2 (also used by eventBridge and lambda function url) - ALB: Application Load Balancer

func StartLambdaHandler

func StartLambdaHandler(h http.Handler)

StartLambdaHandler starts the lambda handler It takes an http.Handler and runs it within a lambda The handler will automatically detect the api gateway version and build the request accordingly It also handles the case where the request is coming from an ALB

Supported integration types: - APIGWv1: API Gateway v1 - APIGWv2: API Gateway v2 (also used by eventBridge and lambda function url) - ALB: Application Load Balancer

Types

type APIGatewayResponse

type APIGatewayResponse struct {
	events.APIGatewayProxyResponse
}

APIGatewayResponse represents the response format required by AWS API Gateway. It contains the status code, headers, and body of the HTTP response.

func (APIGatewayResponse) GetBody

func (r APIGatewayResponse) GetBody() string

GetBody returns the response body as a string. If the body is base64 encoded, it will be decoded before returning.

func (APIGatewayResponse) GetHeaders

func (r APIGatewayResponse) GetHeaders() http.Header

GetHeaders returns the HTTP headers of the response

func (APIGatewayResponse) GetStatusCode

func (r APIGatewayResponse) GetStatusCode() int

GetStatusCode returns the HTTP status code of the response

type IntegrationType

type IntegrationType int

IntegrationType represents the type of AWS integration

const (
	// IntegrationTypeUnknown represents an unknown or unsupported integration type
	IntegrationTypeUnknown IntegrationType = iota
	// IntegrationTypeAPIGWv1 represents API Gateway v1 integration
	IntegrationTypeAPIGWv1
	// IntegrationTypeAPIGWv2 represents API Gateway v2 integration
	IntegrationTypeAPIGWv2
	// IntegrationTypeALB represents Application Load Balancer integration
	IntegrationTypeALB
)

Integration types supported by the package

func GetIntegrationType

func GetIntegrationType(httpRequest *http.Request) IntegrationType

GetIntegrationType determines the AWS integration type from the HTTP request context. Returns IntegrationTypeUnknown if the integration type cannot be determined.

func (IntegrationType) String

func (i IntegrationType) String() string

type LambdaRequest

type LambdaRequest struct {
	Type    IntegrationType
	ALB     *events.ALBTargetGroupRequest
	APIGWv1 *events.APIGatewayProxyRequest
	APIGWv2 *events.APIGatewayV2HTTPRequest
}

LambdaRequest is the request object for the lambda handler It is used to detect the integration type and build the request accordingly

func (*LambdaRequest) UnmarshalJSON

func (r *LambdaRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals the LambdaRequest from a JSON object

type LambdaRequestContextKey

type LambdaRequestContextKey string

LambdaRequestContextKey is used to store and retrieve Lambda-specific request context values

const (
	// LambdaRequestContextKeyOriginalRequest is the context key for storing the original Lambda request
	LambdaRequestContextKeyOriginalRequest LambdaRequestContextKey = "originalRequest"
	// LambdaRequestContextKeyIntegrationType is the context key for storing the integration type
	LambdaRequestContextKeyIntegrationType LambdaRequestContextKey = "integrationType"
)

type Response

type Response interface {
	GetStatusCode() int
	GetHeaders() http.Header
	GetBody() string
}

Response represents a Lambda response that can be returned by the handler

Directories

Path Synopsis
lambdas
rest-api command
Package main demonstrates how to use the lambdahttp package to create a REST API using standard Go HTTP handlers in AWS Lambda.
Package main demonstrates how to use the lambdahttp package to create a REST API using standard Go HTTP handlers in AWS Lambda.

Jump to

Keyboard shortcuts

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