lamb

package module
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2020 License: MIT Imports: 11 Imported by: 0

README

lamb

Build Status Coverage Status Go Report Card

Provides the following utilities to simplify working with AWS lambda.

  • Handlers for API Gateway, S3 and DynamoDB
  • HTTP request parsing with JSON support and request body validation
  • HTTP response writer with JSON support
  • Custom error type with JSON support
  • Logging using zerolog
  • Logs with stacktrace

Request body parsing

Use the bind method to unmarshal the response body to a struct

type requestBody struct {
	Name   string `json:"name"`
}

handler := lamb.Handle(func(c *lamb.Context) error {
	var b requestBody
	err := c.Bind(&b)

	...
})

Request body validation

Implement the Validate method on the struct

type requestBody struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

func (b requestBody) Validate() error {
	if b.Status == "" {
		return errors.New("status empty")
	}
	return nil
}

handler := lamb.Handle(func(c *lamb.Context) error {
	var b requestBody
	err := c.Bind(&b)
	
	// work with requestBody.Name or err == "status empty"
	
	return c.JSON(http.StatusOK, responseBody)
}

Response writer

There are several methods provided to simplify writing HTTP responses.

handler := lamb.Handle(func(c *lamb.Context) error {
	...
	return c.JSON(http.StatusOK, responseBody)
})

lamb.OK(responseBody) sets the HTTP status code to http.StatusOK and marshals responseBody as JSON.

Errors

Custom Errors

You can pass custom lamb errors and also map then to HTTP status codes

handler := lamb.Handle(func(c *lamb.Context) error {
	return c.Error(lamb.Err{
		Status: http.StatusBadRequest,
		Code:   "INVALID_QUERY_PARAM",
		Detail: "Invalid query param",
		Params: map[string]string{
			"custom": "content",
		},
	})
})

Writes the the following response

{
  "code": "INVALID_QUERY_PARAM",
  "detail": "Invalid query param",
  "params": {
    "custom": "content"
  }
}

where params is type interface{} to support arbitrary data in responses.

Bubbling errors up

Go errors returned in the handler are automatically marshalled to a generic json HTTP response and the status code is set to 500. These errors are also logged. If you wrap the source error with eris a stack trace is included in the log.

Access the logger
func(c *lamb.Context) error {
    c.Logger.Log().Str("my_custom_field", "33").Msg("It worked!") // {"my_custom_field":"33","time":"2020-01-08T09:27:07Z","caller":"/path/to/file.go:125","message":"It worked!"}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInternalServer = Err{
	Status: http.StatusInternalServerError,
	Code:   "INTERNAL_SERVER_ERROR",
	Detail: "Internal server error",
}

ErrInternalServer is a standard error to represent server failures

View Source
var ErrInvalidBody = Err{
	Status: http.StatusBadRequest,
	Code:   "INVALID_REQUEST_BODY",
	Detail: "Invalid request body",
}

ErrInvalidBody is a standard error to represent an invalid request body

Functions

func NewDynamoDBHandler added in v0.5.1

func NewDynamoDBHandler(handlerFunc DynamoDBStreamHandlerFunc) func(ctx context.Context, r events.DynamoDBEvent) error

NewDynamoDBHandler adapts the lamb APIGatewayProxyHandlerFunc to the AWS lambda handler that is passed to lambda.Start

func NewS3Handler added in v0.5.0

func NewS3Handler(handlerFunc S3HandlerFunc) func(ctx context.Context, r events.S3Event) error

NewS3Handler adapts the lamb APIGatewayProxyHandlerFunc to the AWS lambda handler that is passed to lambda.Start

Types

type APIGatewayProxyContext added in v0.5.0

type APIGatewayProxyContext struct {
	Context  context.Context
	Logger   zerolog.Logger
	Request  events.APIGatewayProxyRequest
	Response events.APIGatewayProxyResponse
}

APIGatewayProxyContext provides convenience methods for working with API Gateway requests and responses

func (*APIGatewayProxyContext) Bind added in v0.5.0

func (c *APIGatewayProxyContext) Bind(v interface{}) error

Bind attempts to populate the provided struct with data from the HTTP request body. It also performs validation if the provided struct implements `Validatable`

func (*APIGatewayProxyContext) Created added in v0.5.0

func (c *APIGatewayProxyContext) Created(location string) error

Created is a convenient method for writing HTTP Status 201 API Gateway responses. It is opinionated in that it sets the resource location header. If you do not want this use

c.JSON(http.StatusCreated, nil)

instead.

func (*APIGatewayProxyContext) Header added in v0.5.0

func (c *APIGatewayProxyContext) Header(k, v string)

Header writes the provided header to the API Gateway response

func (*APIGatewayProxyContext) JSON added in v0.5.0

func (c *APIGatewayProxyContext) JSON(statusCode int, body interface{}) error

JSON writes the provided body and status code to the API Gateway response

func (*APIGatewayProxyContext) OK added in v0.5.0

func (c *APIGatewayProxyContext) OK(body interface{}) error

OK is a convenient method for writing the provided body and HTTP Status 200 to the API Gateway responses.

type APIGatewayProxyHandler

type APIGatewayProxyHandler = func(ctx context.Context, r events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)

APIGatewayProxyHandler is the handler function for lambda events that originate from API Gateway

func NewAPIGatewayProxyHandler added in v0.5.0

func NewAPIGatewayProxyHandler(handlerFunc APIGatewayProxyHandlerFunc) APIGatewayProxyHandler

NewAPIGatewayProxyHandler adapts the lamb APIGatewayProxyHandlerFunc to the AWS lambda handler that is passed to lambda.Start

type APIGatewayProxyHandlerFunc added in v0.5.0

type APIGatewayProxyHandlerFunc func(ctx *APIGatewayProxyContext) error

APIGatewayProxyHandlerFunc is the lamb handler that users of this library implement. It gives access to convenience methods via `ctx`

type DynamoDBContext added in v0.5.1

type DynamoDBContext struct {
	Context context.Context
	Logger  zerolog.Logger
	Event   events.DynamoDBEventRecord
}

APIGatewayProxyContext provides convenience methods for working with API Gateway requests and responses

func (*DynamoDBContext) Bind added in v0.5.1

func (c *DynamoDBContext) Bind(attributes map[string]events.DynamoDBAttributeValue, v interface{}) error

Bind attempts to populate the provided struct with data from the HTTP request body. It also performs validation if the provided struct implements `Validatable`

func (*DynamoDBContext) EventType added in v0.5.1

type DynamoDBStreamHandler added in v0.5.2

type DynamoDBStreamHandler func(ctx context.Context, r events.DynamoDBEvent) error

DynamoDBStreamHandler is the DynamoDB event handler func for AWS lambda

type DynamoDBStreamHandlerFunc added in v0.5.2

type DynamoDBStreamHandlerFunc func(ctx *DynamoDBContext) error

DynamoDBStreamHandlerFunc is the lamb handler that users of this library implement. It gives access to convenience methods via `ctx`

type Err

type Err struct {
	Status int         `json:"-"`
	Code   string      `json:"code"`
	Detail string      `json:"detail"`
	Params interface{} `json:"params,omitempty"`
}

Err is the error type returned to consumers of the API

func (Err) Error

func (err Err) Error() string

Error implements Go's error condition

type S3Context added in v0.5.0

type S3Context struct {
	Context context.Context
	Logger  zerolog.Logger
	Event   events.S3EventRecord
}

APIGatewayProxyContext provides convenience methods for working with API Gateway requests and responses

type S3Handler added in v0.5.0

type S3Handler func(ctx context.Context, r events.S3Event) error

S3Handler is the S3 event handler func for AWS lambda

type S3HandlerFunc added in v0.5.0

type S3HandlerFunc func(ctx *S3Context) error

S3HandlerFunc is the lamb handler that users of this library implement. It gives access to convenience methods via `ctx`

type Validatable

type Validatable interface {
	Validate() error
}

Validatable is implemented by the request body struct. Example:

     type requestBody struct {
	      Name   string `json:"name"`
	      Status string `json:"status"`
     }

     func (b body) Validate() error {
	      if b.Status == "" {
		    return errors.New("status empty")
	      }
	      return nil
     }

This will then be validated in `ctx.Bind`

Jump to

Keyboard shortcuts

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