ridge

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2024 License: MIT Imports: 18 Imported by: 18

README

ridge

AWS Lambda HTTP Proxy integration event bridge to Go's net/http.

Example

ridge is a bridge to convert request/response payload of API Gateway / ALB / Function URLs to Go's net/http.Request and net/http.ResponseWriter.

package main

import (
	"fmt"
	"net/http"

	"github.com/fujiwara/ridge"
)

func main() {
	var mux = http.NewServeMux()
	mux.HandleFunc("/", handleRoot)
	mux.HandleFunc("/hello", handleHello)
	ridge.Run(":8080", "/", mux)
}

func handleHello(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "Hello %s\n", r.FormValue("name"))
}

func handleRoot(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintln(w, "Hello World")
	fmt.Fprintln(w, r.URL)
}

This code works on AWS Lambda and also as a standalone HTTP server.

If you run this code on AWS Lambda, you can access the function via API Gateway, ALB, or Functinon URLs. ridge converts the request payload to Go's net/http.Request, and the response that your app returns converts to the payload of Lambda.

You can access the function via Go's net/http server if you run this code as a standalone HTTP server.

So you can develop and test your Lambda function locally without deploying to AWS.

Also, you can switch the runtime environment between AWS Lambda and a standalone HTTP server on Amazon ECS, Amazon EC2, or AWS AppRunner without any code and built binarie changes.

ridge.Run(address, prefix, handler)

ridge.Run(address, prefix, handler) works as below.

  • If a process is running on Lambda (AWS_EXECUTION_ENV or AWS_LAMBDA_RUNTIME_API environment variable defined),
    • Call lambda.Start()
  • Otherwise start a net/http server using path prefix and address.
    • path prefix is used to strip the prefix from the request path.
ridge.ToRequestV1(*http.Request)

ridge.ToRequestV1(*http.Request) converts a net/http.Request to an API Gateway V1 event payload.

This function helps call your ridge application handler directly from another service that can invoke Lambda.

For example, you can invoke ridge application on Lambda from EventBridge, Step Functions, or another Lambda function with the payload that ridge.ToRequestV1 returns.

req, _ := http.NewRequest("GET", "http://example.com/hello?name=ridge", nil)
payload, _ := ridge.ToRequestV1(req)
b, _ := json.Marshal(payload)
input := &lambda.InvokeInput{
	FunctionName:   aws.String("your-ridge-function"),
	InvocationType: types.InvocationTypeRequestResponse,
	Payload:        b,
}
result, _ := svc.Invoke(input)
// ...
ridge.ToRequestV2(*http.Request)

ridge.ToRequestV2(*http.Request) converts a net/http.Request to an API Gateway V2 event payload.

Custom request builder

You can use a custom request builder to convert the AWS Lambda invoke payload to net/http.Request.

r := ridge.New(":8080", "/", mux)
r.RequestBuilder = func(payload json.RawMessage) (*http.Request, error) {
    // your custom request builder
}
r.Run()

default request builder is ridge.NewRequest.

LICENSE

The MIT License (MIT)

Copyright (c) 2016- FUJIWARA Shunichiro

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultContentType = "text/plain; charset=utf-8"

DefaultContentType is a default content-type when missing in response.

View Source
var PayloadVersion string

PayloadVersion when this variable set, Ridge disables auto detection payload version.

View Source
var ProxyProtocol bool

ProxyProtocol is a flag to support PROXY Protocol

View Source
var TextMimeTypes = []string{"image/svg+xml", "application/json", "application/xml"}

TextMimeTypes is a list of identified as text.

Functions

func NewRequest

func NewRequest(event json.RawMessage) (*http.Request, error)

NewRequest creates *net/http.Request from a Request.

func Run

func Run(address, prefix string, mux http.Handler)

Run runs http handler on AWS Lambda runtime or net/http's server.

func RunWithContext added in v0.6.0

func RunWithContext(ctx context.Context, address, prefix string, mux http.Handler)

RunWithContext runs http handler on AWS Lambda runtime or net/http's server with context.

Types

type LogEvent

type LogEvent struct {
	ID        string `json:"id"`
	Timestamp int64  `json:"timestamp"`
	Message   string `json:"message"`
}

type LogStream

type LogStream struct {
	MessageType         string     `json:"messageType"`
	Owner               string     `json:"owner"`
	LogGroup            string     `json:"logGroup"`
	LogStream           string     `json:"logStream"`
	SubscriptionFilters []string   `json:"subscriptionFilters"`
	LogEvents           []LogEvent `json:"logEvents"`
}

func DecodeLogStream

func DecodeLogStream(event json.RawMessage) (*LogStream, error)

DecodeLogStream decodes CloudwatchLogs stream passed to a lambda function.

Example
package main

import (
	"encoding/json"
	"log"

	"github.com/aws/aws-lambda-go/lambda"
	"github.com/fujiwara/ridge"
)

func main() {
	lambda.Start(func(event json.RawMessage) (interface{}, error) {
		logStream, err := ridge.DecodeLogStream(event)
		if err != nil {
			return nil, err
		}
		for _, e := range logStream.LogEvents {
			//
			log.Println(e.Message)
		}
		return "", nil
	})
}
Output:

type Message

type Message struct {
	Awslogs struct {
		Data []byte `json:"data"`
	} `json:"awslogs"`
}

type Request

type Request = RequestV1

Request is alias to RequestV1

type RequestContextV1 added in v0.2.0

type RequestContextV1 struct {
	AccountID    string            `json:"accountId"`
	APIID        string            `json:"apiId"`
	HTTPMethod   string            `json:"httpMethod"`
	Identity     map[string]string `json:"identity"`
	RequestID    string            `json:"requestId"`
	ResourceID   string            `json:"resourceId"`
	ResourcePath string            `json:"resourcePath"`
	Stage        string            `json:"stage"`
}

RequestContextV1 represents request contest object (v1.0).

type RequestContextV2 added in v0.2.0

type RequestContextV2 struct {
	AccountID    string `json:"accountId"`
	APIID        string `json:"apiId"`
	DomainName   string `json:"domainName"`
	DomainPrefix string `json:"domainPrefix"`
	HTTP         struct {
		Method    string `json:"method"`
		Path      string `json:"path"`
		Protocol  string `json:"protocol"`
		SourceIP  string `json:"sourceIp"`
		UserAgent string `json:"userAgent"`
	} `json:"http"`
	RequestID string `json:"requestId"`
	RouteID   string `json:"routeId"`
	RouteKey  string `json:"routeKey"`
	Stage     string `json:"stage"`
	Time      string `json:"time"`
	TimeEpoch int64  `json:"timeEpoch"`
}

RequestContextV2 represents request context for v2.0

type RequestV1 added in v0.2.0

type RequestV1 struct {
	Version                         string              `json:"version"`
	Body                            string              `json:"body"`
	Headers                         map[string]string   `json:"headers"`
	MultiValueHeaders               http.Header         `json:"multiValueHeaders"`
	HTTPMethod                      string              `json:"httpMethod"`
	Path                            string              `json:"path"`
	PathParameters                  map[string]string   `json:"pathParameters"`
	QueryStringParameters           map[string]string   `json:"queryStringParameters"`
	MultiValueQueryStringParameters map[string][]string `json:"multiValueQueryStringParameters"`
	Resource                        string              `json:"resource"`
	StageVariables                  map[string]string   `json:"stageVariables"`
	RequestContext                  RequestContextV1    `json:"requestContext"`
	IsBase64Encoded                 bool                `json:"isBase64Encoded"`
}

RequestV1 represents an HTTP request received by an API Gateway proxy integrations. (v1.0) https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html

func ToRequestV1 added in v0.8.0

func ToRequestV1(r *http.Request) (RequestV1, error)

ToRequestV1 converts *http.Request to RequestV1.

type RequestV2 added in v0.2.0

type RequestV2 struct {
	Version               string            `json:"version"`
	RouteKey              string            `json:"routeKey"`
	RawPath               string            `json:"rawPath"`
	RawQueryString        string            `json:"rawQueryString"`
	Cookies               []string          `json:"cookies"`
	Headers               map[string]string `json:"headers"`
	QueryStringParameters map[string]string `json:"queryStringParameters"`
	RequestContext        RequestContextV2  `json:"requestContext"`
	Body                  string            `json:"body"`
	IsBase64Encoded       bool              `json:"isBase64Encoded"`
	StageVariables        map[string]string `json:"stageVariables"`
}

RequestV2 represents an HTTP request received by an API Gateway proxy integrations. (v2.0) https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html

func ToRequestV2 added in v0.8.0

func ToRequestV2(r *http.Request) (RequestV2, error)

ToRequestV2 converts *http.Request to RequestV2.

type RequetContext added in v0.2.0

type RequetContext = RequestContextV1

RequstContext is alias to RequestContextV1

type Response

type Response struct {
	StatusCode        int               `json:"statusCode"`
	Headers           map[string]string `json:"headers"`
	MultiValueHeaders http.Header       `json:"multiValueHeaders"`
	Cookies           []string          `json:"cookies"`
	Body              string            `json:"body"`
	IsBase64Encoded   bool              `json:"isBase64Encoded"`
}

Response represents a response for API Gateway proxy integration.

type ResponseWriter

type ResponseWriter struct {
	bytes.Buffer
	// contains filtered or unexported fields
}

ResponeWriter represents a response writer implements http.ResponseWriter.

func NewResponseWriter

func NewResponseWriter() *ResponseWriter

NewResponseWriter creates ResponseWriter

func (*ResponseWriter) Header

func (w *ResponseWriter) Header() http.Header

func (*ResponseWriter) Response

func (w *ResponseWriter) Response() Response

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(code int)

type Ridge added in v0.9.0

type Ridge struct {
	Address        string
	Prefix         string
	Mux            http.Handler
	RequestBuilder func(json.RawMessage) (*http.Request, error)
}

Ridge is a struct to run http handler on AWS Lambda runtime or net/http's server.

func New added in v0.9.0

func New(address, prefix string, mux http.Handler) *Ridge

New creates a new Ridge.

func (*Ridge) Run added in v0.9.0

func (r *Ridge) Run()

Run runs http handler on AWS Lambda runtime or net/http's server.

func (*Ridge) RunWithContext added in v0.9.0

func (r *Ridge) RunWithContext(ctx context.Context)

RunWithContext runs http handler on AWS Lambda runtime or net/http's server with context.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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