framework

package
v0.0.0-...-473356e Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2019 License: Apache-2.0 Imports: 39 Imported by: 2

Documentation

Index

Constants

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAllow                         = "Allow"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

Variables

View Source
var (
	// ErrNameNotProvided is thrown when a name is not provided
	ErrNameNotProvided = errors.New("no name was provided in the HTTP body")
)
View Source
var Log = logrus.New()

Log uses Logrus for logging and will hook to CloudWatch...But could also be used to hook to other centralized logging services.

Functions

func GetCognitoTriggerType

func GetCognitoTriggerType(evt map[string]interface{}) string

GetCognitoTriggerType returns the name of the struct for the Cognito trigger

func GetQueueNameFromARN

func GetQueueNameFromARN(arn string) string

GetQueueNameFromARN will get the SQS queue name given the ARN string

func RPC

func RPC(functionName string, message map[string]interface{}) (map[string]interface{}, error)

RPC will make the remote procedure call (invoke another lambda)

func ValidAccessTokenMiddleware

func ValidAccessTokenMiddleware(ctx context.Context, d *HandlerDependencies, req *APIGatewayProxyRequest, res *APIGatewayProxyResponse, params url.Values) bool

ValidAccessTokenMiddleware is helper middleware to verify a JWT from an `acess_token` cookie. It makes no determinations based on claims, it just looks for a valid token. A configured CognitoAppClient must be provided.

Types

type APIGatewayProxyRequest

type APIGatewayProxyRequest events.APIGatewayProxyRequest

APIGatewayProxyRequest alias for incoming APIGatewayProxyRequest events

func (*APIGatewayProxyRequest) Cookie

func (req *APIGatewayProxyRequest) Cookie(name string) (*http.Cookie, error)

Cookie will get a cookie from the APIGatewayProxyRequest by parsing the header using Go's http package.

func (*APIGatewayProxyRequest) Cookies

func (req *APIGatewayProxyRequest) Cookies() ([]*http.Cookie, error)

Cookies will get all cookies from the APIGatewayProxyRequest by parsing the header using Go's http package.

func (*APIGatewayProxyRequest) GetBody

func (req *APIGatewayProxyRequest) GetBody() (string, error)

GetBody will return the request body if passed in the event. It's base64 encoded.

func (*APIGatewayProxyRequest) GetForm

func (req *APIGatewayProxyRequest) GetForm() (map[string]interface{}, error)

GetForm will return a Form struct from a form-data body if passed in the request event.

func (*APIGatewayProxyRequest) GetHeader

func (req *APIGatewayProxyRequest) GetHeader(key string) string

GetHeader will return the value for a given header key (case insensitive). If there are no values associated with the key, GetHeader returns "".

func (*APIGatewayProxyRequest) GetJSONBody

func (req *APIGatewayProxyRequest) GetJSONBody() (map[string]interface{}, error)

GetJSONBody will return the request body as map if passed in the event as a JSON string (which would be base64 encoded).

func (*APIGatewayProxyRequest) GetParam

func (req *APIGatewayProxyRequest) GetParam(key string) string

GetParam returns a querystring parameter given its key name or empty string if not set.

func (*APIGatewayProxyRequest) IP

func (req *APIGatewayProxyRequest) IP() string

IP returns the visitor's IP address from the request event struct.

func (*APIGatewayProxyRequest) UserAgent

func (req *APIGatewayProxyRequest) UserAgent() string

UserAgent returns the visitor's browser agent.

type APIGatewayProxyRequestContext

type APIGatewayProxyRequestContext events.APIGatewayProxyRequestContext

APIGatewayProxyRequestContext alias for APIGatewayProxyRequestContext

type APIGatewayProxyResponse

type APIGatewayProxyResponse events.APIGatewayProxyResponse

APIGatewayProxyResponse alias for APIGatewayProxyResponse events, additional functionality added by helpers.go

func (*APIGatewayProxyResponse) Error

func (res *APIGatewayProxyResponse) Error(status int, e error)

Error returns an error message with a status code, format based on content type header.

func (*APIGatewayProxyResponse) GetHeader

func (res *APIGatewayProxyResponse) GetHeader(key string) string

GetHeader will return the value for a given response header key (case insensitive). Works the same as GetHeader() for request.

func (*APIGatewayProxyResponse) HTML

func (res *APIGatewayProxyResponse) HTML(status int, html string)

HTML sets an HTML header and returns a response with status code.

func (*APIGatewayProxyResponse) HTMLError

func (res *APIGatewayProxyResponse) HTMLError(status int, e error)

HTMLError will return an error message in HTML with a status code.

func (*APIGatewayProxyResponse) JSON

func (res *APIGatewayProxyResponse) JSON(status int, body interface{})

JSON sends a JSON response with status code.

func (*APIGatewayProxyResponse) JSONError

func (res *APIGatewayProxyResponse) JSONError(status int, e error)

JSONError will return an error message in a simple JSON object with a status code.

func (*APIGatewayProxyResponse) JSONP

func (res *APIGatewayProxyResponse) JSONP(status int, callback string, body interface{})

JSONP sends a JSONP response with status code.

func (*APIGatewayProxyResponse) Redirect

func (res *APIGatewayProxyResponse) Redirect(status int, url string)

Redirect redirects the request with status code.

func (*APIGatewayProxyResponse) SetBodyError

func (res *APIGatewayProxyResponse) SetBodyError(e error)

SetBodyError will set an error response body based on header content type (plain text if no content type set) This function defines what the body format will be. One can choose to not use this helper function to return custom errors.

func (*APIGatewayProxyResponse) SetHeader

func (res *APIGatewayProxyResponse) SetHeader(key string, value string)

SetHeader will set a APIGatewayProxyResponse header replacing any existing value.

func (*APIGatewayProxyResponse) SetStatus

func (res *APIGatewayProxyResponse) SetStatus(status int)

SetStatus will set the status code for the response.

func (*APIGatewayProxyResponse) String

func (res *APIGatewayProxyResponse) String(status int, s string)

String returns a plain text response with status code.

func (*APIGatewayProxyResponse) XML

func (res *APIGatewayProxyResponse) XML(status int, i interface{})

XML sends an XML response with status code.

func (*APIGatewayProxyResponse) XMLError

func (res *APIGatewayProxyResponse) XMLError(status int, e error)

XMLError will return an error message in XML with a status code.

func (*APIGatewayProxyResponse) XMLPretty

func (res *APIGatewayProxyResponse) XMLPretty(status int, i interface{}, indent string)

XMLPretty sends an indented XML response with status code.

type Aegis

type Aegis struct {
	Handlers
	Log             *logrus.Logger
	AWSClientTracer func(c *client.Client)
	Tracer          TraceStrategy
	TraceContext    context.Context
	Custom          map[string]interface{}
	Services
	Filters struct {
		Handler struct {
			BeforeServices []func(*context.Context, map[string]interface{})
			Before         []func(*context.Context, map[string]interface{})
			After          []func(*context.Context, interface{}, error) (interface{}, error)
		}
	}
}

Aegis is the framework's super interface, it holds various configurations and services While it is possible to use many of the framework's interfaces and routers/handlers individually, it's often more convenient to use this main interface to avoid unnecessary SDK calls, etc.

func New

func New(handlers Handlers) *Aegis

New will return a new Aegis interface with handlers (many, but not all, handlers are routers with many handlers)

func (*Aegis) ConfigureLogger

func (a *Aegis) ConfigureLogger(logger *logrus.Logger)

ConfigureLogger will set a custom logrus Logger, overriding the default which just goes to stdout (and to CloudWatch). Logrus has been chosen for it's pluggability and extensive list of hooks. Send to Bugsnag, Fluentd, InfluxDB, Slack and more. See: https://github.com/sirupsen/logrus

func (*Aegis) ConfigureService

func (a *Aegis) ConfigureService(name string, cfg func(context.Context, map[string]interface{}) interface{})

ConfigureService will configure an AegisService

func (*Aegis) GetVariable

func (a *Aegis) GetVariable(key string) string

GetVariable will retrieve an "Aegis Variable" from Services.Variables or OS environment variable fallback

func (*Aegis) RPC

func (a *Aegis) RPC(functionName string, message map[string]interface{}) (map[string]interface{}, error)

RPC makes an Aegis remote procedure call (invokes another Lambda) with tracing support

func (*Aegis) Start

func (a *Aegis) Start()

Start will tell all handlers to listen for events, it's designed to be similar to lambda.Start()

func (*Aegis) StartServer

func (a *Aegis) StartServer(cfg ...StandAloneCfg)

StartServer will tell all handlers to listen for events, but will do so through a local HTTP server This allows for easy local dev or even running functions outside of AWS Lambda

func (*Aegis) StartSingle

func (a *Aegis) StartSingle(cfg ...StandAloneCfg)

StartSingle will tell all handlers to listen for events, but will receive its event via command line flag

type CloudWatchEvent

type CloudWatchEvent events.CloudWatchEvent

CloudWatchEvent alias for CloudWatchEvent events

type CognitoAppClient

type CognitoAppClient struct {
	Region                   string
	UserPoolID               string
	ClientID                 string
	ClientSecret             string
	Domain                   string
	WellKnownJWKs            *jwk.Set
	BaseURL                  string
	HostedLoginURL           string
	HostedLogoutURL          string
	HostedSignUpURL          string
	RedirectURI              string
	LogoutRedirectURI        string
	TokenEndpoint            string
	Base64BasicAuthorization string
	Tracer                   XRayTraceStrategy
}

CognitoAppClient is an interface for working with AWS Cognito

func NewCognitoAppClient

func NewCognitoAppClient(cfg *CognitoAppClientConfig) (*CognitoAppClient, error)

NewCognitoAppClient returns a new CognitoAppClient interface configured for the given Cognito user pool and client

func (*CognitoAppClient) GetTokens

func (c *CognitoAppClient) GetTokens(code string, scope []string) (CognitoToken, error)

GetTokens will make a POST request to the Cognito TOKEN endpoint to exchange a code for an access token

func (*CognitoAppClient) ParseAndVerifyJWT

func (c *CognitoAppClient) ParseAndVerifyJWT(t string) (*jwt.Token, error)

ParseAndVerifyJWT will parse and verify a JWT, if an error is returned the token is invalid, only a valid token will be returned

https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt Amazon Cognito returns three tokens: the ID token, access token, and refresh token—the ID token contains the user fields defined in the Amazon Cognito user pool.

To verify the signature of an Amazon Cognito JWT, search for the key with a key ID that matches the key ID of the JWT, then use libraries to decode the token and verify the signature.

Be sure to also verify that:

  • The token is not expired.
  • The audience ("aud") in the payload matches the app client ID created in the Cognito user pool.

type CognitoAppClientConfig

type CognitoAppClientConfig struct {
	Region            string                 `json:"region"`
	PoolID            string                 `json:"poolId"`
	Domain            string                 `json:"domain"`
	ClientID          string                 `json:"clientId"`
	ClientSecret      string                 `json:"clientSecret"`
	RedirectURI       string                 `json:"redirectUri"`
	LogoutRedirectURI string                 `json:"logoutRedirectUri"`
	TraceContext      context.Context        `json:"-"`
	AWSClientTracer   func(c *client.Client) `json:"-"`
}

CognitoAppClientConfig defines required info to build a new CognitoAppClient

type CognitoEvent

type CognitoEvent events.CognitoEvent

CognitoEvent alias (NOT a Cognito Trigger event, this is for sync)

type CognitoHandler

type CognitoHandler func(context.Context, *HandlerDependencies, map[string]interface{}) (map[string]interface{}, error)

CognitoHandler handles routed trigger events, note that these must return a map[string]interface{} response

type CognitoRouter

type CognitoRouter struct {
	PoolID string
	Tracer TraceStrategy
	// contains filtered or unexported fields
}

CognitoRouter struct provides an interface to handle Cognito trigger events (routers can be for a specific pool or any)

func NewCognitoRouter

func NewCognitoRouter(rootHandler ...CognitoHandler) *CognitoRouter

NewCognitoRouter simply returns a new CognitoRouter struct and behaves a bit like Router, it even takes an optional rootHandler or "fall through" catch all

func NewCognitoRouterForPool

func NewCognitoRouterForPool(poolID string, rootHandler ...CognitoHandler) *CognitoRouter

NewCognitoRouterForPool is the same as NewCognitoRouter except it's for a specific pool ID (you could also set the PoolID field after using the other function)

func (*CognitoRouter) Handle

func (r *CognitoRouter) Handle(triggerSource string, handler func(context.Context, *HandlerDependencies, map[string]interface{}) (map[string]interface{}, error))

Handle will register a handler for a given Cognito trigger source List of triggerSources here: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-lambda-trigger-syntax-shared.html

func (*CognitoRouter) LambdaHandler

func (r *CognitoRouter) LambdaHandler(ctx context.Context, d *HandlerDependencies, evt map[string]interface{}) (map[string]interface{}, error)

LambdaHandler handles Cognito trigger events.

func (*CognitoRouter) Listen

func (r *CognitoRouter) Listen()

Listen will start an S3 even listener that handles incoming object based events (put, delete, etc.)

func (*CognitoRouter) PreSignUp

func (r *CognitoRouter) PreSignUp(handler func(context.Context, *HandlerDependencies, map[string]interface{}) (map[string]interface{}, error))

PreSignUp is the same as Handle only the triggerSource is already implied. It handles any PreSignUp_SignUp event.

type CognitoToken

type CognitoToken struct {
	IDToken      string `json:"id_token"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
	TokenType    string `json:"token_type"`
	Error        string `json:"error"`
}

CognitoToken defines a token struct for JSON responses from Cognito TOKEN endpoint

type CognitoTriggerCallerContext

type CognitoTriggerCallerContext struct {
	AWSSDKVersion string `json:"awsSdkVersion"`
	ClientID      string `json:"clientId"`
}

CognitoTriggerCallerContext contains information about the caller (should be the same for all triggers)

type CognitoTriggerCommon

type CognitoTriggerCommon struct {
	Version       string                      `json:"version"`
	TriggerSource string                      `json:"triggerSource"`
	Region        string                      `json:"region"`
	UserPoolID    string                      `json:"userPoolId"`
	CallerContext CognitoTriggerCallerContext `json:"callerContext"`
	UserName      string                      `json:"userName"`
}

CognitoTriggerCommon contains common data from events sent by AWS Cognito (should be the same for all triggers)

type CognitoTriggerCustomMessage

type CognitoTriggerCustomMessage struct {
	CognitoTriggerCommon
	Request struct {
		UserAttributes    map[string]interface{} `json:"userAttributes"`
		CodeParameter     string                 `json:"codeParameter"`
		UsernameParameter string                 `json:"usernameParameter"`
	} `json:"request"`
	Response struct {
		SMSMessage   string `json:"smsMessage"`
		EmailMessage string `json:"emailMessage"`
		EmailSubject string `json:"emailSubject"`
	} `json:"response"`
}

CognitoTriggerCustomMessage is invoked before a verification or MFA message is sent, allowing you to customize the message dynamically. Note that static custom messages can be edited on the Verifications panel. triggerSource: CustomMessage_ResendCode

type CognitoTriggerPostAuthentication

type CognitoTriggerPostAuthentication struct {
	CognitoTriggerCommon
	Request struct {
		UserAttributes map[string]interface{} `json:"userAttributes"`
		NewDeviceUsed  bool                   `json:"newDeviceUsed"`
	} `json:"request"`
	Response map[string]interface{} `json:"response"`
}

CognitoTriggerPostAuthentication is invoked after a user is authenticated, allowing you to add custom logic, for example for analytics. triggerSource: PostAuthentication_Authentication

type CognitoTriggerPostConfirmation

type CognitoTriggerPostConfirmation struct {
	CognitoTriggerCommon
	Request struct {
		UserAttributes map[string]interface{} `json:"userAttributes"`
	} `json:"request"`
	Response map[string]interface{} `json:"response"`
}

CognitoTriggerPostConfirmation is invoked after a user is confirmed, allowing you to send custom messages or to add custom logic, for example for analytics. triggerSource: PostConfirmation_ConfirmSignUp, PostConfirmation_ConfirmForgotPassword

type CognitoTriggerPreAuthentication

type CognitoTriggerPreAuthentication struct {
	CognitoTriggerCommon
	Request struct {
		UserAttributes map[string]interface{} `json:"userAttributes"`
		ValidationData map[string]interface{} `json:"validationData"`
	} `json:"request"`
	Response map[string]interface{} `json:"response"`
}

CognitoTriggerPreAuthentication is invoked when a user submits their information to be authenticated, allowing you to perform custom validations to accept or deny the sign in request. triggerSource: PreAuthentication_Authentication

type CognitoTriggerPreSignup

type CognitoTriggerPreSignup struct {
	CognitoTriggerCommon
	Request struct {
		UserAttributes map[string]interface{} `json:"userAttributes"`
		ValidationData map[string]interface{} `json:"validationData"`
	} `json:"request"`
	Response struct {
		AutoConfirmUser bool `json:"autoConfirmUser"`
		AutoVerifyEmail bool `json:"autoVerifyEmail"`
		AutoVerifyPhone bool `json:"autoVerifyPhone"`
	} `json:"response"`
}

CognitoTriggerPreSignup is invoked when a user submits their information to sign up, allowing you to perform custom validation to accept or deny the sign up request. triggerSource: PreSignUp_AdminCreateUser, PreSignUp_SignUp

type CognitoTriggerTokenGeneration

type CognitoTriggerTokenGeneration struct {
	CognitoTriggerCommon
	Request struct {
		UserAttributes     map[string]interface{} `json:"userAttributes"`
		GroupConfiguration map[string]interface{} `json:"groupConfiguration"`
	} `json:"request"`
	Response map[string]interface{} `json:"response"` // default is map[claimsOverrideDetails: <nil>]
}

CognitoTriggerTokenGeneration is invoked before the token generation, allowing you to customize the claims in the identity token. triggerSource: TokenGeneration_HostedAuth

type DefaultHandler

type DefaultHandler func(context.Context, *HandlerDependencies, *map[string]interface{}) (interface{}, error)

DefaultHandler is used when the message type can't be identified as anything else, completely optional to use

type HandlerDependencies

type HandlerDependencies struct {
	Services *Services
	Log      *logrus.Logger
	Tracer   TraceStrategy
	Custom   map[string]interface{}
}

HandlerDependencies defines dependencies to be injected into each handler

func (*HandlerDependencies) GetVariable

func (d *HandlerDependencies) GetVariable(key string) string

GetVariable will retrieve an "Aegis Variable" from Services.Variables or OS environment variable fallback

type HandlerFuncAdapter

type HandlerFuncAdapter struct {
	core.RequestAccessor
	HandlerFunc http.HandlerFunc
	Handler     http.Handler
}

HandlerFuncAdapter is an interface for adapting and handling Lambda APIGatewayProxyRequests to standard http Requests

func NewHandlerAdapter

func NewHandlerAdapter(handlerFunc http.HandlerFunc) *HandlerFuncAdapter

NewHandlerAdapter creates a new stdlib http.HandlerFunc adapter allowing the use of standard http request handling

func (*HandlerFuncAdapter) Proxy

Proxy will proxy Lambda APIGatewayProxyRequests through a standard http handler and return an APIGatewayProxyResponse

type Handlers

type Handlers struct {
	Router         *Router
	Tasker         *Tasker
	RPCRouter      *RPCRouter
	S3ObjectRouter *S3ObjectRouter
	SESRouter      *SESRouter
	SQSRouter      *SQSRouter
	CognitoRouter  *CognitoRouter
	DefaultHandler DefaultHandler
}

Handlers defines a set of Aegis framework Lambda handlers

func (*Handlers) Listen

func (h *Handlers) Listen()

Listen will start a general listener which determines the proper handler to used based on incoming events. NOTE: Using handlers directly this way skips on injecting dependencies into the handlers.

type Middleware

Middleware is just like the RouteHandler type, but has a boolean return. True means to keep processing the rest of the middleware chain, false means end.

type NoTraceStrategy

type NoTraceStrategy struct {
}

NoTraceStrategy interface does nothing (good for unit tests and disabling tracing)

func (NoTraceStrategy) BeginSegment

func (t NoTraceStrategy) BeginSegment(ctx context.Context, name string) (context.Context, interface{})

BeginSegment in this case does nothing

func (NoTraceStrategy) BeginSubsegment

func (t NoTraceStrategy) BeginSubsegment(ctx context.Context, name string) (context.Context, interface{})

BeginSubsegment in this case does nothing

func (NoTraceStrategy) Capture

func (t NoTraceStrategy) Capture(ctx context.Context, name string, fn func(context.Context) error) error

Capture in this case just executes the function it's wrapping

func (NoTraceStrategy) CaptureAsync

func (t NoTraceStrategy) CaptureAsync(ctx context.Context, name string, fn func(context.Context) error)

CaptureAsync in this case just executes the function it's wrapping

func (NoTraceStrategy) CloseSegment

func (t NoTraceStrategy) CloseSegment(segment interface{}, err error)

CloseSegment in this case does nothing

func (NoTraceStrategy) CloseSubsegment

func (t NoTraceStrategy) CloseSubsegment(segment interface{}, err error)

CloseSubsegment in this case does nothing

func (NoTraceStrategy) Record

func (t NoTraceStrategy) Record(dataType string, data interface{})

Record in this case does nothing

type RPCHandler

type RPCHandler func(context.Context, *HandlerDependencies, map[string]interface{}) (map[string]interface{}, error)

RPCHandler is similar to and other router/handler but it returns a map[string]interface{} in addition to an error

type RPCRouter

type RPCRouter struct {
	Tracer TraceStrategy
	// contains filtered or unexported fields
}

RPCRouter struct provides an interface to handle remote procedures (other Lambdas invoking the one listening via AWS SDK)

func NewRPCRouter

func NewRPCRouter(rootHandler ...RPCHandler) *RPCRouter

NewRPCRouter simply returns a new RPCRouter struct and behaves a bit like Router, it even takes an optional rootHandler or "fall through" catch all

func (*RPCRouter) Handle

func (r *RPCRouter) Handle(name string, handler RPCHandler)

Handle will register a handler for a given remote procedure name

func (*RPCRouter) LambdaHandler

func (r *RPCRouter) LambdaHandler(ctx context.Context, d *HandlerDependencies, evt map[string]interface{}) (map[string]interface{}, error)

LambdaHandler is a native AWS Lambda Go handler function. Handles a remote procedure call (invocation via SDK with a special event format).

func (*RPCRouter) Listen

func (r *RPCRouter) Listen()

Listen will start an RPC listener which acts much like a task handler except that it handles special RPC events instead

type RouteHandler

RouteHandler is similar to "net/http" Handler, except there is no response writer. Instead the *APIGatewayProxyResponse is manipulated and returned directly.

type Router

type Router struct {
	LoggingEnabled bool
	URIVersion     string
	GatewayPort    string
	Tracer         TraceStrategy
	// contains filtered or unexported fields
}

Router name says it all.

func NewRouter

func NewRouter(rootHandler RouteHandler) *Router

NewRouter creates a new router. Take the root/fall through route like how the default mux works. Only difference is in this case, you have to specific one.

func (*Router) DELETE

func (r *Router) DELETE(path string, handler RouteHandler, middleware ...Middleware)

DELETE same as Handle only the method is already implied.

func (*Router) GET

func (r *Router) GET(path string, handler RouteHandler, middleware ...Middleware)

GET same as Handle only the method is already implied.

func (*Router) HEAD

func (r *Router) HEAD(path string, handler RouteHandler, middleware ...Middleware)

HEAD same as Handle only the method is already implied.

func (*Router) Handle

func (r *Router) Handle(method, path string, handler RouteHandler, middleware ...Middleware)

Handle takes an http handler, method and pattern for a route.

func (*Router) LambdaHandler

LambdaHandler is a native AWS Lambda Go handler function (no more shim).

func (*Router) Listen

func (r *Router) Listen()

Listen will start the internal router and listen for Lambda events to forward to registered routes.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler RouteHandler, middleware ...Middleware)

OPTIONS same as Handle only the method is already implied.

func (*Router) PATCH

func (r *Router) PATCH(path string, handler RouteHandler, middleware ...Middleware)

PATCH same as Handle only the method is already implied.

func (*Router) POST

func (r *Router) POST(path string, handler RouteHandler, middleware ...Middleware)

POST same as Handle only the method is already implied.

func (*Router) PUT

func (r *Router) PUT(path string, handler RouteHandler, middleware ...Middleware)

PUT same as Handle only the method is already implied.

func (*Router) Use

func (r *Router) Use(middleware ...Middleware)

Use will set middleware on the Router that gets used by all handled routes.

func (*Router) UseStandard

func (r *Router) UseStandard(middleware ...func(h http.Handler) http.Handler)

UseStandard will set stdMiddleware on the Router that gets used by all handled routes. This is standard, idiomatic, Go http.Handler middleware.

type S3Event

type S3Event events.S3Event

S3Event alias

type S3ObjectHandler

type S3ObjectHandler struct {
	Handler func(context.Context, *HandlerDependencies, *S3Event) error
	Event   string
}

S3ObjectHandler handles routed events in a different way than other handlers The router used for HTTP request like events is similar because it deals with http methods and paths, but not file extensions...Also, S3 events are slightly different than http methods. So this handler actually is a struct with a Handler function like normal, but then also an event type match and an object key ("file path") glob matcher.

type S3ObjectRouter

type S3ObjectRouter struct {
	Bucket string
	Tracer TraceStrategy
	// contains filtered or unexported fields
}

S3ObjectRouter struct provides an interface to handle S3 object events (routers can be for a specific bucket or all buckets) https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html

func NewS3ObjectRouter

func NewS3ObjectRouter(rootHandler ...S3ObjectHandler) *S3ObjectRouter

NewS3ObjectRouter simply returns a new S3ObjectRouter struct and behaves a bit like Router, it even takes an optional rootHandler or "fall through" catch all

func NewS3ObjectRouterForBucket

func NewS3ObjectRouterForBucket(bucket string, rootHandler ...S3ObjectHandler) *S3ObjectRouter

NewS3ObjectRouterForBucket is the same as NewS3ObjectRouter except it's for a specific bucket (you could also set the bucket field after using the other function)

func (*S3ObjectRouter) CompleteMultipartUpload

func (r *S3ObjectRouter) CompleteMultipartUpload(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

CompleteMultipartUpload is the same as Handle only the event is already implied.

func (*S3ObjectRouter) Copy

func (r *S3ObjectRouter) Copy(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Copy is the same as Handle only the event is already implied.

func (*S3ObjectRouter) Created

func (r *S3ObjectRouter) Created(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Created is the same as Handle only the event is already implied. It handles any ObjectCreated event.

func (*S3ObjectRouter) Delete

func (r *S3ObjectRouter) Delete(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Delete is the same as Handle only the event is already implied.

func (*S3ObjectRouter) DeleteMarkerCreated

func (r *S3ObjectRouter) DeleteMarkerCreated(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

DeleteMarkerCreated is the same as Handle only the event is already implied.

func (*S3ObjectRouter) Handle

func (r *S3ObjectRouter) Handle(event string, keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Handle will register a handler for a given S3 object event and key name glob match

func (*S3ObjectRouter) LambdaHandler

func (r *S3ObjectRouter) LambdaHandler(ctx context.Context, d *HandlerDependencies, evt S3Event) error

LambdaHandler handles S3 events.

func (*S3ObjectRouter) Listen

func (r *S3ObjectRouter) Listen()

Listen will start an S3 event listener that handles incoming object based events (put, delete, etc.)

func (*S3ObjectRouter) Post

func (r *S3ObjectRouter) Post(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Post is the same as Handle only the event is already implied.

func (*S3ObjectRouter) Put

func (r *S3ObjectRouter) Put(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Put is the same as Handle only the event is already implied.

func (*S3ObjectRouter) ReducedRedundancyLostObject

func (r *S3ObjectRouter) ReducedRedundancyLostObject(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

ReducedRedundancyLostObject is the same as Handle only the event is already implied.

func (*S3ObjectRouter) Removed

func (r *S3ObjectRouter) Removed(keyMatch string, handler func(context.Context, *HandlerDependencies, *S3Event) error)

Removed is the same as Handle only the event is already implied. It handles any ObjectRemoved event.

type SESHandler

SESHandler handles incoming SES e-mail message events

type SESRouter

type SESRouter struct {
	Domain string
	Tracer TraceStrategy
	// contains filtered or unexported fields
}

SESRouter struct provides an interface to handle SES events (routers can be per Domain much like S3ObjectRouter can be per Bucket)

func NewSESRouter

func NewSESRouter(rootHandler ...SESHandler) *SESRouter

NewSESRouter simply returns a new SESRouter struct and behaves a bit like Router, it even takes an optional rootHandler or "fall through" catch all

func NewSESRouterForDomain

func NewSESRouterForDomain(domain string, rootHandler ...SESHandler) *SESRouter

NewSESRouterForDomain is the same as NewSESRouter except it's for a specific domain (you could also set the domain field after using the other function)

func (*SESRouter) Handle

func (r *SESRouter) Handle(addressMatcher string, handler func(context.Context, *HandlerDependencies, *SimpleEmailEvent) error)

Handle will register a handler for a given e-mail address match (regex). Note that routers can be per domain so this address match could match two different domains and therefore be used in two different routers, ie. `user@domainA.com` `user@domainB.com` matching on addressMatcher value `user@`.

func (*SESRouter) LambdaHandler

func (r *SESRouter) LambdaHandler(ctx context.Context, d *HandlerDependencies, evt SimpleEmailEvent) error

LambdaHandler handles SES received e-mail events.

func (*SESRouter) Listen

func (r *SESRouter) Listen()

Listen will start an SES event listener that handles incoming object based events (put, delete, etc.)

type SQSEvent

type SQSEvent events.SQSEvent

SQSEvent alias for SQS events

type SQSHandler

type SQSHandler struct {
	Handler           func(context.Context, *HandlerDependencies, *SQSEvent) error
	AttributeName     string
	AttributeStrValue string
}

SQSHandler handles incoming SQS events. Matching on attribute name and its string value (ie. 1 is "1" and binary values are base64 strings)

type SQSRouter

type SQSRouter struct {
	Queue  string
	Tracer TraceStrategy
	// contains filtered or unexported fields
}

SQSRouter struct provides an interface to handle SQS events (routers can be per Domain much like S3ObjectRouter can be per Bucket)

func NewSQSRouter

func NewSQSRouter(rootHandler ...func(context.Context, *HandlerDependencies, *SQSEvent) error) *SQSRouter

NewSQSRouter simply returns a new SQSRouter struct and behaves a bit like Router, it even takes an optional rootHandler or "fall through" catch all

func NewSQSRouterForQueue

func NewSQSRouterForQueue(queue string, rootHandler ...func(context.Context, *HandlerDependencies, *SQSEvent) error) *SQSRouter

NewSQSRouterForQueue returns a new SQSRouter for a specific SQS queue, it will only route events coming from the given queue

func (*SQSRouter) Handle

func (r *SQSRouter) Handle(attrName string, attrStrValue string, handler func(context.Context, *HandlerDependencies, *SQSEvent) error)

Handle will register a handler for a given attribute name and its string value match (1 would be "1" and binary values would be base64 strings). Note that routers can be per queue so this match could match two different queues and therefore be used in two different routers.

func (*SQSRouter) LambdaHandler

func (r *SQSRouter) LambdaHandler(ctx context.Context, d *HandlerDependencies, evt SQSEvent) error

LambdaHandler handles SQS events.

func (*SQSRouter) Listen

func (r *SQSRouter) Listen()

Listen will start an SES event listener that handles incoming object based events (put, delete, etc.)

type Services

type Services struct {
	Cognito   *CognitoAppClient
	Variables map[string]string
	// contains filtered or unexported fields
}

Services defines core framework services such as auth

type SimpleEmailEvent

type SimpleEmailEvent events.SimpleEmailEvent

SimpleEmailEvent alias for SES Email events (recipient rules)

type StandAloneCLICfg

type StandAloneCLICfg struct {
	PrettyPrint   bool
	HideLogOutput bool
}

StandAloneCLICfg has some options for the CLI when running "stand alone" functions

type StandAloneCfg

type StandAloneCfg struct {
	Port              string
	AllowHeaders      []string
	AllowMethods      []string
	AllowOrigin       string
	AdditionalHeaders map[string]string
	CLI               StandAloneCLICfg
}

StandAloneCfg allows the local HTTP server to be configured, passed to StartServer()

type TaskHandler

type TaskHandler func(context.Context, *HandlerDependencies, map[string]interface{}) error

TaskHandler is similar to RouteHandler except there is no response or middleware

type Tasker

type Tasker struct {
	IgnoreFunctionScope bool
	Tracer              TraceStrategy
	// contains filtered or unexported fields
}

Tasker struct provides an interface to handle scheduled tasks

func NewTasker

func NewTasker(rootHandler ...TaskHandler) *Tasker

NewTasker simply returns a new Tasker struct and behaves a bit like Router, it even takes an optional rootHandler or "fall through" catch all

func (*Tasker) Handle

func (t *Tasker) Handle(name string, handler TaskHandler)

Handle will register a handler for a given task name

func (*Tasker) LambdaHandler

func (t *Tasker) LambdaHandler(ctx context.Context, d *HandlerDependencies, evt map[string]interface{}) error

LambdaHandler is a native AWS Lambda Go handler function. Handles a CloudWatch event.

func (*Tasker) Listen

func (t *Tasker) Listen()

Listen will start a task listener which acts much like a router except that it handles scheduled task events instead

type TraceStrategy

type TraceStrategy interface {
	// Record sends data to a trace service (either immediately or sometimes upon Capture() or CaptureAsync(), it depends on the strategy)
	Record(dataType string, data interface{})
	// BeginSegment starts a new trace segment (should be fairly common for anything that traces, though can be implemented to do nothing)
	BeginSegment(ctx context.Context, name string) (context.Context, interface{})
	// BeginSubsegment starts a new subsegment if applicable
	BeginSubsegment(ctx context.Context, name string) (context.Context, interface{})
	// CloseSegment will close a segment
	CloseSegment(interface{}, error)
	// CloseSubsegment will close a subsegment
	CloseSubsegment(interface{}, error)
	// Capture traces the provided synchronous function
	Capture(ctx context.Context, name string, fn func(context.Context) error) error
	// CaptureAsync traces an arbitrary code segment within a goroutine
	CaptureAsync(ctx context.Context, name string, fn func(context.Context) error)
}

TraceStrategy interface allows for customized tracing (AWS X-Ray is Aegis' default).

You'll notice a lot of interface{} values here, that's because we don't know what the segment or data will be. In the case of AWS X-Ray the segment and subsegment values are both a Segment struct. Recorded data could be annotations, metadata, and more.

The strategy supports the concept of opening and closing segments and subsegments, recording data, as well as capturing (synchronously and asynchronously) or "wrapping" function calls to be traced. Somewhere. It also concerns itself with context of course.

type XRayTraceStrategy

type XRayTraceStrategy struct {
	Annotation        map[string]interface{}
	Metadata          map[string]interface{}
	NamespaceMetadata map[string]map[string]interface{}
	Error             error
	AWSClientTracer   func(c *client.Client)
}

XRayTraceStrategy interface uses AWS X-Ray

func (XRayTraceStrategy) BeginSegment

func (t XRayTraceStrategy) BeginSegment(ctx context.Context, name string) (context.Context, interface{})

BeginSegment will begin a new trace segment, useful when running locally as AWS Lambda already does this

func (XRayTraceStrategy) BeginSubsegment

func (t XRayTraceStrategy) BeginSubsegment(ctx context.Context, name string) (context.Context, interface{})

BeginSubsegment will begin a new trace sub-segment, useful within handlers

func (XRayTraceStrategy) Capture

func (t XRayTraceStrategy) Capture(ctx context.Context, name string, fn func(context.Context) error) (err error)

Capture traces the provided synchronous function by using XRay Cpature() which puts a beginning and closing subsegment around its execution

func (XRayTraceStrategy) CaptureAsync

func (t XRayTraceStrategy) CaptureAsync(ctx context.Context, name string, fn func(context.Context) error)

CaptureAsync traces an arbitrary code segment within a goroutine by using XRay CaptureAsync()

func (XRayTraceStrategy) CloseSegment

func (t XRayTraceStrategy) CloseSegment(segment interface{}, err error)

CloseSegment will just call AWS X-Ray's Segment.Close()

func (XRayTraceStrategy) CloseSubsegment

func (t XRayTraceStrategy) CloseSubsegment(segment interface{}, err error)

CloseSubsegment will just call AWS X-Ray's Segment.Close()

func (*XRayTraceStrategy) Record

func (t *XRayTraceStrategy) Record(dataType string, data interface{})

Record will pass along data to be sent to the tracing service (X-Ray in this case), note that this is not context aware. In XRayTraceStrategy, this data is sent along with the context in Capture().

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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