lmdrouter

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2022 License: Apache-2.0 Imports: 18 Imported by: 0

README

lmdrouter

Lambda HTTP Router

Forked from aquasecurity/lmdrouter

This library is not executable by itself but instead is imported by other programs that implement AWS Lambda HTTP REST APIs.

Build

make build

Test

make test

Documentation

Overview

Package lmdrouter is a simple-to-use library for writing AWS Lambda functions in Go that listen to events of type API Gateway Proxy Req (represented by the `events.APIGatewayProxyRequest` type of the github.com/aws-lambda-go/events package).

The library allows creating functions that can match reqs based on their URI, just like an HTTP server that uses the standard https://golang.org/pkg/net/http/#ServeMux (or any other community-built routing library such as https://github.com/julienschmidt/httprouter or https://github.com/go-chi/chi) would. The interface provided by the library is very similar to these libraries and should be familiar to anyone who has written HTTP applications in Go.

Use Case

When building large cloud-native applications, there's a certain balance to strike when it comes to deployment of APIs. On one side of the scale, each API endpoint has its own lambda function. This provides the greatest flexibility, but is extremely difficult to maintain. On the other side of the scale, there can be one lambda function for the entire API. This provides the least flexibility, but is the easiest to maintain. Both are probably not a good idea.

With `lmdrouter`, one can create small lambda functions for different aspects of the API. For example, if your application model contains multiple domains (e.g. articles, authors, topics, etc...), you can create one lambda function for each domain, and deploy these independently (e.g. everything below "/api/articles" is one lambda function, everything below "/api/authors" is another function). This is also useful for applications where different teams are in charge of different parts of the API.

Features

* Supports all HTTP methods.

* Supports middleware functions at a global and per-resource level.

* Supports path parameters with a simple ":<name>" format (e.g. "/posts/:id").

* Provides ability to automatically "unmarshal" an API Gateway req to an arbitrary Go struct, with data coming either from path and query string parameters, or from the req body (only JSON reqs are currently supported). See the documentation for the `UnmarshalRequest` function for more information.

* Provides the ability to automatically "marshal" responses of any type to an API Gateway response (only JSON responses are currently generated). See the MarshalResponse function for more information.

* Implements net/http.Handler for local development and general usage outside of an AWS Lambda environment.

Index

Constants

View Source
const (
	AudienceKey  = "aud"
	ExpiresAtKey = "exp"
	IDKey        = "jti"
	IssuedAtKey  = "iat"
	IssuerKey    = "iss"
	NotBeforeKey = "nbf"
	SubjectKey   = "sub"
)

Variables

View Source
var ExposeServerErrors = true

ExposeServerErrors is a boolean indicating whether the HandleError function should expose errors of status code 500 or above to clients. If false, the name of the status code is used as the error message instead.

Functions

func ExtractJWT

func ExtractJWT(headers map[string]string) (jwt.MapClaims, int, error)

func ExtractStandardClaims

func ExtractStandardClaims(mapClaims jwt.MapClaims) (*jwt.StandardClaims, error)

func GenerateJWT

func GenerateJWT(claims jwt.MapClaims) (string, int, error)

func HandleError

func HandleError(err error) (events.APIGatewayProxyResponse, error)

HandleError generates an events.APIGatewayProxyResponse from an error value. If the error is an HTTPError, the response's status code will be taken from the error. Otherwise, the error is assumed to be 500 Internal Server Error. Regardless, all errors will generate a JSON response in the format `{ "code": 500, "error": "something failed" }` This format cannot currently be changed. If you do not wish to expose server errors (i.e. errors whose status code is 500 or above), set the ExposeServerErrors global variable to false.

func HandleHTTPError

func HandleHTTPError(httpStatus int, err error) (events.APIGatewayProxyResponse, error)

func InitializeMapClaims

func InitializeMapClaims(audience string, expiresAt int64, id string, issuedAt int64, issuer string, notBefore int64, subject string) (jwt.MapClaims, error)

InitializeMapClaims embeds all the necessary values for a StandardClaims inside of custom MapClaims. The returned MapClaims can be used to insert any custom values that you need for your own purpose.

func MarshalResponse

func MarshalResponse(httpStatus int, headers map[string]string, data interface{}) (
	events.APIGatewayProxyResponse,
	error,
)

MarshalResponse generated an events.APIGatewayProxyResponse object that can be directly returned via the lambda's handler function. It receives an HTTP status code for the response, a map of HTTP headers (can be empty or nil), and a value (probably a struct) representing the response body. This value will be marshaled to JSON (currently without base 64 encoding).

func MarshalSuccess

func MarshalSuccess(data interface{}) (events.APIGatewayProxyResponse, error)

MarshalSuccess wraps MarshalResponse assuming a 200 OK status code and no custom headers to return. This was such a common use case I felt it necessary to create a wrapper to make everyone's life easier.

func UnmarshalRequest

func UnmarshalRequest(
	req events.APIGatewayProxyRequest,
	body bool,
	target interface{},
) error

UnmarshalRequest "fills" out a target Go struct with data from the req. If body is true, then the req body is assumed to be JSON and simply unmarshaled into the target (taking into account that the req body may be base-64 encoded). After that, or if body is false, the function will traverse the exported fields of the target struct, and fill those that include the "lambda" struct tag with values taken from the req's query string parameters, path parameters and headers, according to the field's struct tag definition. This means a struct value can be filled with data from the body, the path, the query string and the headers at the same time.

Field types are currently limited to string, all integer types, all unsigned integer types, all float types, booleans, slices of the aforementioned types and pointers of these types.

Note that custom types that alias any of the aforementioned types are also accepted and the appropriate constant values will be generated. Boolean fields accept (in a case-insensitive way) the values "1", "true", "on" and "enabled". Any other value is considered false.

Example struct (no body):

type ListPostsInput struct {
    ID          uint64   `lambda:"path.id"`
    Page        uint64   `lambda:"query.page"`
    PageSize    uint64   `lambda:"query.page_size"`
    Search      string   `lambda:"query.search"`
    ShowDrafts  bool     `lambda:"query.show_hidden"`
    Languages   []string `lambda:"header.Accept-Language"`
}

Example struct (JSON body):

type UpdatePostInput struct {
    ID          uint64   `lambda:"path.id"`
    Author      string   `lambda:"header.Author"`
    Title       string   `json:"title"`
    Content     string   `json:"content"`
}

func VerifyJWT

func VerifyJWT(userJWT string) (jwt.MapClaims, int, error)

VerifyJWT accepts the user JWT from the Authorization header and returns the MapClaims OR a http status code and error set

Types

type HTTPError

type HTTPError struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
}

HTTPError is a generic struct type for JSON error responses. It allows the library to assign an HTTP status code for the errors returned by its various functions.

func (HTTPError) Error

func (err HTTPError) Error() string

Error returns a string representation of the error.

type Handler

Handler is a req handler function. It receives a context, and the API Gateway's proxy req object, and returns a proxy response object and an error.

Example:

 func listSomethings(ctx context.Context, req events.APIGatewayProxyRequest) (
     res events.APIGatewayProxyResponse,
     err error,
 ) {
     // parse input
     var input listSomethingsInput
     err = lmdrouter.UnmarshalRequest(req, false, &input)
     if err != nil {
         return lmdrouter.HandleError(err)
     }

     // call some business logic that generates an output struct
     // ...

     return lmdrouter.MarshalResponse(http.StatusOK, nil, output)
}

func DecodeStandardJWTMiddleware

func DecodeStandardJWTMiddleware(next Handler) Handler

DecodeStandardJWTMiddleware attempts to parse a Json Web Token from the req's "Authorization" header. If the Authorization header is missing, or does not contain a valid Json Web Token (JWT) then an error message and appropriate HTTP status code will be returned. If the JWT is correctly set and contains a StandardClaim then the values from tha standard claim will be added to the context object for others to use during their processing.

type Middleware

type Middleware func(Handler) Handler

Middleware is a function that receives a handler function (the next function in the chain, possibly another middleware or the actual handler matched for a req), and returns a handler function. These functions are quite similar to HTTP middlewares in other libraries.

Example middleware that logs all reqs:

func loggerMiddleware(next lmdrouter.Handler) lmdrouter.Handler {
    return func(ctx context.Context, req events.APIGatewayProxyRequest) (
        res events.APIGatewayProxyResponse,
        err error,
    ) {
        format := "[%s] [%s %s] [%d]%s"
        level := "INF"
        var code int
        var extra string

        res, err = next(ctx, req)
        if err != nil {
            level = "ERR"
            code = http.StatusInternalServerError
            extra = " " + err.Error()
        } else {
            code = res.StatusCode
            if code >= 400 {
                level = "ERR"
            }
        }

        log.Printf(format, level, req.HTTPMethod, req.Path, code, extra)

        return res, err
    }
}

type Router

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

Router is the main type of the library. Lambda routes are registered to it, and it's Handler method is used by the lambda to match reqs and execute the appropriate handler.

func NewRouter

func NewRouter(basePath string, middleware ...Middleware) (l *Router)

NewRouter creates a new Router object with a base path and a list of zero or more global middleware functions. The base path is necessary if the lambda function is not going to be mounted to a domain's root (for example, if the function is mounted to "https://my.app/api", then the base path must be "/api"). Use an empty string if the function is mounted to the root of the domain.

func (*Router) GetOptionsHandler

func (l *Router) GetOptionsHandler() Handler

func (*Router) Handler

Handler receives a context and an API Gateway Proxy req, and handles the req, matching the appropriate handler and executing it. This is the method that must be provided to the lambda's `main` function:

package main

import (
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aquasecurity/lmdrouter"
)

var router *lmdrouter.Router

func init() {
    router = lmdrouter.NewRouter("/api", loggerMiddleware, authMiddleware)
    router.Route("GET", "/", listSomethings)
    router.Route("POST", "/", postSomething, someOtherMiddleware)
    router.Route("GET", "/:id", getSomething)
    router.Route("PUT", "/:id", updateSomething)
    router.Route("DELETE", "/:id", deleteSomething)
}

func main() {
    lambda.Start(router.Handler)
}

func (*Router) Route

func (l *Router) Route(method, path string, handler Handler, middleware ...Middleware)

Route registers a new route, with the provided HTTP method name and path, and zero or more local middleware functions.

func (*Router) ServeHTTP

func (l *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServerHTTP implements the net/http.Handler interface in order to allow lmdrouter applications to be used outside of AWS Lambda environments, most likely for local development purposes

Jump to

Keyboard shortcuts

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