proxy

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2017 License: MIT Imports: 10 Imported by: 0

README

API Gateway Proxy request handling support

This package provides an Apex-compatible handler for proxy requests.

Each proxy request matches a wildcard path in AWS API Gateway, which is then converted to a standard http.Request before dispatching using the http.Handler interface.

Usage

Any router or middleware framework supporting the http.Handler interface should be compatible with this adapter.

package main

import (
	"net/http"

	"github.com/apex/go-apex"
	"github.com/apex/go-apex/proxy"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", hello)
	mux.HandleFunc("/foo", foo)
	mux.HandleFunc("/bar", bar)
	apex.Handle(proxy.Serve(mux))
}

...

Notes

Stdout vs Stderr

As with any Apex handler, you must make sure that your handler doesn't write anything to stdout. If your web framework logs to stdout by default, such as Martini, you need to change the logger output to use stderr.

Content-Types passed through as plain text output:

Any output with a Content-Type that doesn't match one of those listed below will be Base64 encoded in the output record. In order for this to be returned from API Gateway correctly, you will need to enable binary support and map the content types containing binary data.

In practice you can usually map all types as binary using the */* pattern for binary support if you aren't using other API Gateway resources which conflict with this.

The text-mode Content-Type regular expressions used by default are:

* text/.*
* application/json
* application/.*\+json
* application/xml
* application/.*\+xml

You can override this by calling proxy.SetTextContentTypes with a list of regular expressions matching the types that should not be Base64 encoded.

Output encoding

API gateway will automatically gzip-encode the output of your API, so it's not necessary to gzip the output of your webapp.

If you use your own gzip encoding, it's likely to interfere with the Base64 output for text content types - this hasn't been tested.

Differences from eawsy

This implementation reuses a large portion of the event definitions from the eawsy AWS Lambda projects:

However, it wraps a web application in an apex-compatible adapter which makes direct calls to an http.Handler instance rather than creating a fake net.Conn and marshalling/unmarshalling the request data.

A ResponseWriter implementation captures the response of the handler and constructs an API Gateway Proxy response.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultTextContentTypes = []string{
	`text/.*`,
	`application/json`,
	`application/.*\+json`,
	`application/xml`,
	`application/.*\+xml`,
}

DefaultTextContentTypes specifies the content types that will not be Base64 encoded by default. See SetTextContentTypes

Functions

func Serve

func Serve(h http.Handler) apex.Handler

Serve adaptes an http.Handler to the apex.Handler interface.

func SetTextContentTypes

func SetTextContentTypes(types []string) error

SetTextContentTypes configures the proxy package to skip Base64 encoding of the response body for responses with a Content-Type header matching one of the provided types. Each type provided is a regular expression pattern.

Types

type Event

type Event struct {
	// The incoming request HTTP method name.
	// Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.
	HTTPMethod string

	// The incoming reauest HTTP headers.
	// Duplicate entries are not supported.
	Headers map[string]string

	// The resource path with raw placeholders as defined in Amazon API Gateway.
	Resource string

	// The incoming request path parameters corresponding to the resource path
	// placeholders values as defined in Resource.
	PathParameters map[string]string

	// The real path corresponding to the path parameters injected into the
	// Resource placeholders.
	Path string

	// The incoming request query string parameters.
	// Duplicate entries are not supported.
	QueryStringParameters map[string]string

	// If used with Amazon API Gateway binary support, it represents the Base64
	// encoded binary data from the client.
	// Otherwise it represents the raw data from the client.
	Body string

	// A flag to indicate if the applicable request payload is Base64 encoded.
	IsBase64Encoded bool

	// The name-value pairs defined as configuration attributes associated with
	// the deployment stage of the API.
	StageVariables map[string]string

	// The contextual information associated with the API call.
	RequestContext *RequestContext
}

Event represents an Amazon API Gateway Proxy Event.

func (*Event) GoString

func (e *Event) GoString() string

GoString returns the string representation.

func (*Event) String

func (e *Event) String() string

String returns the string representation.

type Identity

type Identity struct {
	// The API owner key associated with the API.
	APIKey string

	// The AWS account ID associated with the request.
	AccountID string

	// The User Agent of the API caller.
	UserAgent string

	// The source IP address of the TCP connection making the request to
	// Amazon API Gateway.
	SourceIP string

	// The Amazon Access Key associated with the request.
	AccessKey string

	// The principal identifier of the caller making the request.
	// It is same as the User and interchangeable.
	Caller string

	// The principal identifier of the user making the request.
	// It is same as the Caller and interchangeable.
	User string

	// The Amazon Resource Name (ARN) of the effective user identified after
	// authentication.
	UserARN string

	// The Amazon Cognito identity ID of the caller making the request.
	// Available only if the request was signed with Amazon Cognito credentials.
	CognitoIdentityID string

	// The Amazon Cognito identity pool ID of the caller making the request.
	// Available only if the request was signed with Amazon Cognito credentials.
	CognitoIdentityPoolID string

	// The Amazon Cognito authentication type of the caller making the request.
	// Available only if the request was signed with Amazon Cognito credentials.
	CognitoAuthenticationType string

	// The Amazon Cognito authentication provider used by the caller making the
	// request.
	// Available only if the request was signed with Amazon Cognito credentials.
	CognitoAuthenticationProvider string
}

Identity provides identity information about the API caller.

type RequestContext

type RequestContext struct {
	// The identifier Amazon API Gateway assigns to the API.
	APIID string

	// The identifier Amazon API Gateway assigns to the resource.
	ResourceID string

	// An automatically generated ID for the API call.
	RequestID string

	// The incoming request HTTP method name.
	// Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.
	HTTPMethod string

	// The resource path as defined in Amazon API Gateway.
	ResourcePath string

	// The AWS account ID associated with the API.
	AccountID string

	// The deployment stage of the API call (for example, Beta or Prod).
	Stage string

	// The API caller identification information.
	Identity *Identity

	// If used with Amazon Cognito, it represents the claims returned from the
	// Amazon Cognito user pool after the method caller is successfully
	// authenticated.
	// If used with Amazon API Gateway custom authorizer, it represents the
	// specified key-value pair of the context map returned from the custom
	// authorizer AWS Lambda function.
	Authorizer map[string]string `json:"-"`
}

RequestContext provides contextual information about an Amazon API Gateway Proxy event.

func (*RequestContext) MarshalJSON

func (rc *RequestContext) MarshalJSON() ([]byte, error)

MarshalJSON reverts the effect of type aliasing and struct embedding used during the marshalling step to make the pattern seamless.

func (*RequestContext) UnmarshalJSON

func (rc *RequestContext) UnmarshalJSON(data []byte) error

UnmarshalJSON interprets data as a RequestContext with a special authorizer. It then leverages type aliasing and struct embedding to fill RequestContext with an usual map[string]string.

type Response

type Response struct {
	StatusCode      int               `json:"statusCode"`
	Headers         map[string]string `json:"headers,omitempty"`
	Body            string            `json:"body,omitempty"`
	IsBase64Encoded bool              `json:"isBase64Encoded"`
}

Response defines parameters for a well formed response AWS Lambda should return to Amazon API Gateway. Originally from https://github.com/eawsy/aws-lambda-go-net/blob/master/service/lambda/runtime/net/apigatewayproxy/server.go

type ResponseWriter

type ResponseWriter struct {
	// contains filtered or unexported fields
}

ResponseWriter implements the http.ResponseWriter interface and collects the results of an HTTP request in an API Gateway proxy response object.

func (*ResponseWriter) Header

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

Header returns the header map that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example). To suppress implicit response headers, set their value to nil.

func (*ResponseWriter) Write

func (w *ResponseWriter) Write(bs []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply.

If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

Depending on the HTTP protocol version and the client, calling Write or WriteHeader may prevent future reads on the Request.Body. For HTTP/1.x requests, handlers should read any needed request body data before writing the response. Once the headers have been flushed (due to either an explicit Flusher.Flush call or writing enough data to trigger a flush), the request body may be unavailable. For HTTP/2 requests, the Go HTTP server permits handlers to continue to read the request body while concurrently writing the response. However, such behavior may not be supported by all HTTP/2 clients. Handlers should read before writing if possible to maximize compatibility.

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(status int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

Jump to

Keyboard shortcuts

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