lux

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

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

Go to latest
Published: Apr 10, 2018 License: MIT Imports: 10 Imported by: 2

README

lux

CircleCI Coverage Status GoDoc Go Report Card GitHub license FOSSA Status

A simple package for creating RESTful AWS Lambda functions in Go. Inspired by packages like mux & negroni

usage

func main() {
  // Create a router
  router := lux.NewRouter()

  // Create a custom panic recovery function (optional). This allows you to do things
  // in the event one of your handlers panics.
  router.Recovery(recoverFunc)

  // Configure the logging (optional), anything in stdout or stderr should be
  // logged by AWS.
  router.Logging(os.Stdout, &logrus.JSONFormatter{})

  // Register some middleware
  router.Middleware(middlewareFunc)

  // Configure your routes for different HTTP methods. You can specify headers/params that
  // the request must contain to use this route.
  router.Handler("GET", getFunc).Queries("key", "*")
  router.Handler("PUT", putFunc).Headers("Content-Type", "application/json")
  router.Handler("POST", postFunc).Headers("Content-Type", "application/json")
  router.Handler("DELETE", deleteFunc).Queries("key", "*")

  // Start the lambda.
  lambda.Start(router.ServeHTTP)
}

handlers

Defining a handler is fairly straightforward. You can have multiple handlers per HTTP method. This package attempts to make creating HTTP handlers as similar to the standard library as possible, so provides a signature mirroring a standard HTTP handler. The signature for any handler function is as follows:

func handler(w lux.ResponseWriter, r *lux.Request) {
  encoder := json.NewEncoder(w)

  if err := encoder.Encode("hello world"); err != nil {
    // handle
  }

  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(http.StatusOK)
}

Then you can register your handler function using the Router.Handler method.

router.Handler("GET", handler)

Whenever a GET request is made to the lambda function, the handler will be called. You can also specify which headers must be present for a request to reach your handler. For example, if we only want JSON requests, we can use the Route.Headers method to specify this:

// Require header with value
router.Handler("GET", handler).Headers("Content-Type", "application/json")

// Require header regardless of value
router.Handler("GET", handler).Headers("Content-Type", "*")

We can also perform the same route matching based on query parameters that you would typically see in GET/DELETE requests by using the Router.Queries method:

// Require the query parameter with value
router.Handler("GET", handler).Queries("key", "value")

// Require query parameter regardless of value
router.Handler("GET", handler).Queries("key", "*")

// You can have multiple routes for a single HTTP method that expect different query parameters
router.Handler("GET", handler1).Queries("id", "*")
router.Handler("GET", handler2).Queries("name", "*")

recovery

In the event a process in your handler causes a panic, the router will automatically recover for you. However, if you want to handle recovery yourself, you can provide a custom panic handler. The signature for a panic handler is as follows:

func onPanic(info lux.PanicInfo) {
  // do something with the panic information
}

The PanicInfo type contains the error, stack & request regarding the panic. You can tell the router to use your custom panic handler like so:

router.Recovery(onPanic)

logging

The router uses logrus, a structured logger. You can either choose to disable the logs of the router or you can provide some configuration for it. AWS automatically logs the output of stderr and stdout, so you can specify that the router should log to either of these like this:

router.Logging(os.Stdout, &logrus.JSONFormatter{})

The second parmeter is a logrus formatter, which will output the logs as JSON. You can also provide a custom formatter, see logrus' godoc page for more info on custom formatters

middleware

You can also provide custom middleware functions that can are executed before your handler. These can be registered globally or per-route. You can prevent execution of your handler by using w.WriteHeader method. Any modifications to the response writer that occur during execution of middleware functions will create a response and prevent execution of the handler. Middleware methods are executed in the order they are registered.

func middleware(w lux.ResponseWriter, r *lux.Request) {
  // use an error status to prevent further execution
  w.WriteHeader(http.StatusInternalServerError)

  // changes you make to the request object are propagated to
  // your handlers
  r.Body = "you've changed"
}

You can register the middleware like this:

// Global middleware
router.Middleware(middleware)

// Route specific middleware
router.Handler("GET", getHandler).Middleware(middleware)

Documentation

Overview

Package lux contains types for creating an HTTP router for use in AWS lambda functions. The router supports RESTful HTTP methods & contains configuration for logging, request filtering & panic recovery.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

The HandlerFunc type defines what a handler function should look like.

type Headers

type Headers map[string]string

The Headers type represents the HTTP response headers.

func (Headers) Set

func (h Headers) Set(key, val string)

Set creates a new header with the given key and value.

type PanicInfo

type PanicInfo struct {
	Error   error
	Stack   []byte
	Request Request
}

The PanicInfo type is passed to any custom registered panic handler functions and provides details on the request that caused the panic.

type RecoverFunc

type RecoverFunc func(PanicInfo)

The RecoverFunc type defines what a panic recovery function should look like.

type Request

type Request struct {
	events.APIGatewayProxyRequest

	Context context.Context `json:"-"`
}

The Request type represents an incoming HTTP request.

type Response

The Response type represents an outgoing HTTP response.

type ResponseWriter

type ResponseWriter interface {
	Write([]byte) (int, error)
	WriteHeader(int)
	Header() *Headers
}

The ResponseWriter type allows for interacting with the HTTP response similarly to a triaditional HTTP handler in go.

type Route

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

The Route type defines a route that can be used by the router.

func (*Route) Headers

func (r *Route) Headers(pairs ...string) *Route

Headers allows you to specify headers a request should have in order to use this route. You can use wildcards when you only care about a header's presence rather than its value.

func (*Route) Middleware

func (r *Route) Middleware(fn ...HandlerFunc) *Route

Middleware allows you to apply middleware functions to a specific route, rather than globally to all routes.

func (*Route) Queries

func (r *Route) Queries(pairs ...string) *Route

Queries allows you to specify query parameters and values a request should have in order to use this route. You can use wildcards when you only care about a parameter's presence rather than its value.

type Router

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

The Router type handles incoming requests & routes them to the registered handlers.

func NewRouter

func NewRouter() *Router

NewRouter creates a new lambda router.

func (*Router) Handler

func (r *Router) Handler(method string, fn HandlerFunc) *Route

Handler adds a given handler to the router.

func (*Router) Logging

func (r *Router) Logging(out io.Writer, format logrus.Formatter) *Router

Logging sets the output for logs generated by the router. The logging package used is logrus (https://github.com/sirupsen/logrus). All logs written to os.Stdout and os.Stderr will automatically be picked up by CloudWatch. The logrus.Formatter interface allows you to specify a custom format for logs. By default, the output is JSON

func (*Router) Middleware

func (r *Router) Middleware(fn ...HandlerFunc) *Router

Middleware adds a middleware function to the router. These methods will be called prior to the route handler and allow you to perform processing on the request before your handler is executed.

func (*Router) Recovery

func (r *Router) Recovery(fn RecoverFunc) *Router

Recovery sets a custom recovery handler that allows you to process panics using your own handler. Not providing a recovery handler does not mean that your panics are not handled. When no custom handler is specified your panic will be logged to os.Stdout and execution can resume.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(req Request) (Response, error)

ServeHTTP handles an incoming HTTP request from the AWS API Gateway. If the request matches a registered route then the specified handler will be executed after any registered middleware.

If a handler cannot be found matching the HTTP method, a 405 response will be returned to the client.

If you have specified query or header filters to your route, a request that matches the HTTP method but lacks the required parameters/headers will result in a 406 response.

A panic will result in a 500 response.

Jump to

Keyboard shortcuts

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