lambdarouter

package module
v0.0.0-...-53393fc Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2019 License: MIT Imports: 19 Imported by: 0

README

This router is fully based on https://github.com/dimfeld/httptreemux it was modified for use on AWS Lambda and take all advantage on this

it's possible to use on local with builtin server NOT USE BUILTIN SERVER ON PRODUCTION

Usage

package main

import (
	"context"
	"fmt"
	"github.com/kedric/lambdarouter"
	"github.com/aws/aws-lambda-go/events"
	"log"
)

func Index(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
	return events.APIGatewayProxyResponse{
		StatusCode: 200,
		Body:     "Welcome!\n",
	}, nil
}

func Hello(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	return events.APIGatewayProxyResponse{
		StatusCode: 200,
		Body:       fmt.Sprintf("hello, %s!\n", req.PathParameters["name"]),
	}, nil
}

func main() {
	router := lambdarouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	router.Serve(":8080", nil)
}

Serve

Serve method on router check if AWS_EXECUTION_ENV is set in env if is not set start mux server with port passed in argument else call lambda.Start(...) from aws sdk

on mux server all path has prefixed by /:__stage__ when request oncomming the stage variable is stored in event.RequestContext.Stage

Stage Variables

if you need to pass a stageVariables to lambda with http handler add them on serv

exemple:

var variables = lambdarouter.StageVariables{
	"stagename": {
		"variablename":       "value",
	},
}

router.Serv(":8080", variables)

Authorizer

ON PROGRESS

For use authorizer add handler function by router.SetAuthorizer(handler)

func authorizer (ctx context.Context, request events.APIGatewayCustomAuthorizerRequestTypeRequest) (events.APIGatewayCustomAuthorizerResponse, error) {
	...
}

func main() {
	router := lambdarouter.New()
	router.SetAuthorizer(authorizer)
	router.Serve(":8080", nil)
}

When you use builtin server it was call befor handler and passed on request. When you deploy on lambda create spesific lambda with env variable AUTHORIZER = true.

Documentation

Overview

This is inspired by Julien Schmidt's httprouter, in that it uses a patricia tree, but the implementation is rather different. Specifically, the routing rules are relaxed so that a single path segment may be a wildcard in one route and a static token in another. This gives a nice combination of high performance with a lot of convenience in designing the routing patterns.

Index

Constants

View Source
const (
	Redirect301 RedirectBehavior = iota // Return 301 Moved Permanently
	Redirect307                         // Return 307 HTTP/1.1 Temporary Redirect
	Redirect308                         // Return a 308 RFC7538 Permanent Redirect
	UseHandler                          // Just call the handler function

	RequestURI PathSource = iota // Use r.RequestURI
	URLPath                      // Use r.URL.Path
)

Variables

This section is empty.

Functions

func AddParamsToContext

func AddParamsToContext(ctx context.Context, params map[string]string) context.Context

AddParamsToContext inserts a parameters map into a context using the package's internal context key. Clients of this package should really only use this for unit tests.

func Clean

func Clean(p string) string

Clean is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func CleanPath

func CleanPath(event events.APIGatewayProxyRequest) string

func ContextParams

func ContextParams(ctx context.Context) map[string]string

ContextParams returns the params map associated with the given context if one exists. Otherwise, an empty map is returned.

func GenerateArn

func GenerateArn(event events.APIGatewayProxyRequest) string

func GetForwarded

func GetForwarded(r *http.Request) string

func LambdaGenerateRawQuery

func LambdaGenerateRawQuery(request events.APIGatewayProxyRequest) string

func MethodNotAllowedHandler

func MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request,
	methods map[string]HandlerFunc)

MethodNotAllowedHandler is the default handler for TreeMux.MethodNotAllowedHandler, which is called for patterns that match, but do not have a handler installed for the requested method. It simply writes the status code http.StatusMethodNotAllowed and fills in the `Allow` header value appropriately.

func RequestToLambda

func RequestToLambda(req *http.Request) (events.APIGatewayProxyRequest, error)

func ShowErrorsJsonPanicHandler

func ShowErrorsJsonPanicHandler(w http.ResponseWriter, r *http.Request, err interface{})

func ShowErrorsPanicHandler

func ShowErrorsPanicHandler(w http.ResponseWriter, r *http.Request, err interface{})

ShowErrorsPanicHandler prints a nice representation of an error to the browser. This was taken from github.com/gocraft/web, which adapted it from the Traffic project.

func SimplePanicHandler

func SimplePanicHandler(w http.ResponseWriter, r *http.Request, err interface{})

SimplePanicHandler just returns error 500.

func UseTemplate

func UseTemplate(event events.APIGatewayProxyRequest) string

Types

type ContextGroup

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

ContextGroup is a wrapper around Group, with the purpose of mimicking its API, but with the use of Handle-based handlers. Instead of passing a parameter map via the handler (i.e. httptreemux.HandlerFunc), the path parameters are accessed via the request object's context.

func (*ContextGroup) DELETE

func (cg *ContextGroup) DELETE(path string, handler HandlerFunc)

DELETE is convenience method for handling DELETE requests on a context group.

func (*ContextGroup) GET

func (cg *ContextGroup) GET(path string, handler HandlerFunc)

GET is convenience method for handling GET requests on a context group.

func (*ContextGroup) HEAD

func (cg *ContextGroup) HEAD(path string, handler HandlerFunc)

HEAD is convenience method for handling HEAD requests on a context group.

func (*ContextGroup) Handle

func (cg *ContextGroup) Handle(method, path string, handler HandlerFunc)

Handle allows handling HTTP requests via an Handle, as opposed to an httptreemux.HandlerFunc. Any parameters from the request URL are stored in a map[string]string in the request's context.

func (*ContextGroup) NewContextGroup

func (cg *ContextGroup) NewContextGroup(path string) *ContextGroup

NewContextGroup adds a child context group to its path.

func (*ContextGroup) NewGroup

func (cg *ContextGroup) NewGroup(path string) *ContextGroup

func (*ContextGroup) OPTIONS

func (cg *ContextGroup) OPTIONS(path string, handler HandlerFunc)

OPTIONS is convenience method for handling OPTIONS requests on a context group.

func (*ContextGroup) PATCH

func (cg *ContextGroup) PATCH(path string, handler HandlerFunc)

PATCH is convenience method for handling PATCH requests on a context group.

func (*ContextGroup) POST

func (cg *ContextGroup) POST(path string, handler HandlerFunc)

POST is convenience method for handling POST requests on a context group.

func (*ContextGroup) PUT

func (cg *ContextGroup) PUT(path string, handler HandlerFunc)

PUT is convenience method for handling PUT requests on a context group.

type ContextMux

type ContextMux struct {
	*TreeMux
	*ContextGroup
}

func NewContextMux

func NewContextMux() *ContextMux

NewContextMux returns a TreeMux preconfigured to work with standard http Handler functions and context objects.

func (*ContextMux) DELETE

func (cm *ContextMux) DELETE(path string, handler HandlerFunc)

DELETE is convenience method for handling DELETE requests on a context group.

func (*ContextMux) GET

func (cm *ContextMux) GET(path string, handler HandlerFunc)

GET is convenience method for handling GET requests on a context group.

func (*ContextMux) HEAD

func (cm *ContextMux) HEAD(path string, handler HandlerFunc)

HEAD is convenience method for handling HEAD requests on a context group.

func (*ContextMux) NewGroup

func (cm *ContextMux) NewGroup(path string) *ContextGroup

func (*ContextMux) OPTIONS

func (cm *ContextMux) OPTIONS(path string, handler HandlerFunc)

OPTIONS is convenience method for handling OPTIONS requests on a context group.

func (*ContextMux) PATCH

func (cm *ContextMux) PATCH(path string, handler HandlerFunc)

PATCH is convenience method for handling PATCH requests on a context group.

func (*ContextMux) POST

func (cm *ContextMux) POST(path string, handler HandlerFunc)

POST is convenience method for handling POST requests on a context group.

func (*ContextMux) PUT

func (cm *ContextMux) PUT(path string, handler HandlerFunc)

PUT is convenience method for handling PUT requests on a context group.

type Group

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

func (*Group) DELETE

func (g *Group) DELETE(path string, handler HandlerFunc)

Syntactic sugar for Handle("DELETE", path, handler)

func (*Group) GET

func (g *Group) GET(path string, handler HandlerFunc)

Syntactic sugar for Handle("GET", path, handler)

func (*Group) HEAD

func (g *Group) HEAD(path string, handler HandlerFunc)

Syntactic sugar for Handle("HEAD", path, handler)

func (*Group) Handle

func (g *Group) Handle(method string, path string, handler HandlerFunc)

Path elements starting with : indicate a wildcard in the path. A wildcard will only match on a single path segment. That is, the pattern `/post/:postid` will match on `/post/1` or `/post/1/`, but not `/post/1/2`.

A path element starting with * is a catch-all, whose value will be a string containing all text in the URL matched by the wildcards. For example, with a pattern of `/images/*path` and a requested URL `images/abc/def`, path would contain `abc/def`.

Routing Rule Priority

The priority rules in the router are simple.

1. Static path segments take the highest priority. If a segment and its subtree are able to match the URL, that match is returned.

2. Wildcards take second priority. For a particular wildcard to match, that wildcard and its subtree must match the URL.

3. Finally, a catch-all rule will match when the earlier path segments have matched, and none of the static or wildcard conditions have matched. Catch-all rules must be at the end of a pattern.

So with the following patterns, we'll see certain matches:

router = httptreemux.New()
router.GET("/:page", pageHandler)
router.GET("/:year/:month/:post", postHandler)
router.GET("/:year/:month", archiveHandler)
router.GET("/images/*path", staticHandler)
router.GET("/favicon.ico", staticHandler)

/abc will match /:page
/2014/05 will match /:year/:month
/2014/05/really-great-blog-post will match /:year/:month/:post
/images/CoolImage.gif will match /images/*path
/images/2014/05/MayImage.jpg will also match /images/*path, with all the text after /images stored in the variable path.
/favicon.ico will match /favicon.ico

Trailing Slashes

The router has special handling for paths with trailing slashes. If a pattern is added to the router with a trailing slash, any matches on that pattern without a trailing slash will be redirected to the version with the slash. If a pattern does not have a trailing slash, matches on that pattern with a trailing slash will be redirected to the version without.

The trailing slash flag is only stored once for a pattern. That is, if a pattern is added for a method with a trailing slash, all other methods for that pattern will also be considered to have a trailing slash, regardless of whether or not it is specified for those methods too.

This behavior can be turned off by setting TreeMux.RedirectTrailingSlash to false. By default it is set to true. The specifics of the redirect depend on RedirectBehavior.

One exception to this rule is catch-all patterns. By default, trailing slash redirection is disabled on catch-all patterns, since the structure of the entire URL and the desired patterns can not be predicted. If trailing slash removal is desired on catch-all patterns, set TreeMux.RemoveCatchAllTrailingSlash to true.

router = httptreemux.New()
router.GET("/about", pageHandler)
router.GET("/posts/", postIndexHandler)
router.POST("/posts", postFormHandler)

GET /about will match normally.
GET /about/ will redirect to /about.
GET /posts will redirect to /posts/.
GET /posts/ will match normally.
POST /posts will redirect to /posts/, because the GET method used a trailing slash.

func (*Group) NewGroup

func (g *Group) NewGroup(path string) *Group

Add a sub-group to this group

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handler HandlerFunc)

Syntactic sugar for Handle("OPTIONS", path, handler)

func (*Group) PATCH

func (g *Group) PATCH(path string, handler HandlerFunc)

Syntactic sugar for Handle("PATCH", path, handler)

func (*Group) POST

func (g *Group) POST(path string, handler HandlerFunc)

Syntactic sugar for Handle("POST", path, handler)

func (*Group) PUT

func (g *Group) PUT(path string, handler HandlerFunc)

Syntactic sugar for Handle("PUT", path, handler)

func (*Group) UsingContext

func (g *Group) UsingContext() *ContextGroup

UsingContext wraps the receiver to return a new instance of a ContextGroup. The returned ContextGroup is a sibling to its wrapped Group, within the parent TreeMux. The choice of using a *Group as the receiver, as opposed to a function parameter, allows chaining while method calls between a TreeMux, Group, and ContextGroup. For example:

tree := httptreemux.New()
group := tree.NewGroup("/api")

group.GET("/v1", func(w http.ResponseWriter, r *http.Request, params map[string]string) {
    w.Write([]byte(`GET /api/v1`))
})

group.UsingContext().GET("/v2", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`GET /api/v2`))
})

http.ListenAndServe(":8080", tree)

type HandlerFunc

The params argument contains the parameters parsed from wildcards and catch-alls in the URL.

type LookupResult

type LookupResult struct {
	// StatusCode informs the caller about the result of the lookup.
	// This will generally be `http.StatusNotFound` or `http.StatusMethodNotAllowed` for an
	// error case. On a normal success, the statusCode will be `http.StatusOK`. A redirect code
	// will also be used in the case
	StatusCode int
	// contains filtered or unexported fields
}

LookupResult contains information about a route lookup, which is returned from Lookup and can be passed to ServeLookupResult if the request should be served.

type PanicHandler

type PanicHandler func(http.ResponseWriter, *http.Request, interface{})

type PathSource

type PathSource int

type RedirectBehavior

type RedirectBehavior int

RedirectBehavior sets the behavior when the router redirects the request to the canonical version of the requested URL using RedirectTrailingSlash or RedirectClean. The default behavior is to return a 301 status, redirecting the browser to the version of the URL that matches the given pattern.

On a POST request, most browsers that receive a 301 will submit a GET request to the redirected URL, meaning that any data will likely be lost. If you want to handle and avoid this behavior, you may use Redirect307, which causes most browsers to resubmit the request using the original method and request body.

Since 307 is supposed to be a temporary redirect, the new 308 status code has been proposed, which is treated the same, except it indicates correctly that the redirection is permanent. The big caveat here is that the RFC is relatively recent, and older browsers will not know what to do with it. Therefore its use is not recommended unless you really know what you're doing.

Finally, the UseHandler value will simply call the handler function for the pattern.

type StageVariables

type StageVariables map[string]map[string]string

type TreeMux

type TreeMux struct {
	StageVariables StageVariables

	Group

	// The default PanicHandler just returns a 500 code.
	PanicHandler PanicHandler

	// The default NotFoundHandler is http.NotFound.
	NotFoundHandler HandlerFunc

	// Any OPTIONS request that matches a path without its own OPTIONS handler will use this handler,
	// if set, instead of calling MethodNotAllowedHandler.
	OptionsHandler HandlerFunc

	// MethodNotAllowedHandler is called when a pattern matches, but that
	// pattern does not have a handler for the requested method. The default
	// handler just writes the status code http.StatusMethodNotAllowed and adds
	// the required Allowed header.
	// The methods parameter contains the map of each method to the corresponding
	// handler function.
	MethodNotAllowedHandler func(context.Context, events.APIGatewayProxyRequest, string) (events.APIGatewayProxyResponse, error)

	// HeadCanUseGet allows the router to use the GET handler to respond to
	// HEAD requests if no explicit HEAD handler has been added for the
	// matching pattern. This is true by default.
	HeadCanUseGet bool

	// RedirectCleanPath allows the router to try clean the current request path,
	// if no handler is registered for it, using CleanPath from github.com/dimfeld/httppath.
	// This is true by default.
	RedirectCleanPath bool

	// RedirectTrailingSlash enables automatic redirection in case router doesn't find a matching route
	// for the current request path but a handler for the path with or without the trailing
	// slash exists. This is true by default.
	RedirectTrailingSlash bool

	// RemoveCatchAllTrailingSlash removes the trailing slash when a catch-all pattern
	// is matched, if set to true. By default, catch-all paths are never redirected.
	RemoveCatchAllTrailingSlash bool

	// RedirectBehavior sets the default redirect behavior when RedirectTrailingSlash or
	// RedirectCleanPath are true. The default value is Redirect301.
	RedirectBehavior RedirectBehavior

	// RedirectMethodBehavior overrides the default behavior for a particular HTTP method.
	// The key is the method name, and the value is the behavior to use for that method.
	RedirectMethodBehavior map[string]RedirectBehavior

	// PathSource determines from where the router gets its path to search.
	// By default it pulls the data from the RequestURI member, but this can
	// be overridden to use URL.Path instead.
	//
	// There is a small tradeoff here. Using RequestURI allows the router to handle
	// encoded slashes (i.e. %2f) in the URL properly, while URL.Path provides
	// better compatibility with some utility functions in the http
	// library that modify the Request before passing it to the router.
	PathSource PathSource

	// EscapeAddedRoutes controls URI escaping behavior when adding a route to the tree.
	// If set to true, the router will add both the route as originally passed, and
	// a version passed through URL.EscapedPath. This behavior is disabled by default.
	EscapeAddedRoutes bool

	// If present, override the default context with this one.
	DefaultContext context.Context

	// SafeAddRoutesWhileRunning tells the router to protect all accesses to the tree with an RWMutex. This is only needed
	// if you are going to add routes after the router has already begun serving requests. There is a potential
	// performance penalty at high load.
	SafeAddRoutesWhileRunning bool
	// contains filtered or unexported fields
}

func New

func New() *TreeMux

func (*TreeMux) Dump

func (t *TreeMux) Dump() string

Dump returns a text representation of the routing tree.

func (*TreeMux) Lookup

func (t *TreeMux) Lookup(request events.APIGatewayProxyRequest) (LookupResult, bool)

Lookup performs a lookup without actually serving the request or mutating the request or response. The return values are a LookupResult and a boolean. The boolean will be true when a handler was found or the lookup resulted in a redirect which will point to a real handler. It is false for requests which would result in a `StatusNotFound` or `StatusMethodNotAllowed`.

Regardless of the returned boolean's value, the LookupResult may be passed to ServeLookupResult to be served appropriately.

func (*TreeMux) Serve

func (r *TreeMux) Serve(addr string, stages StageVariables) error

func (*TreeMux) ServeHTTP

func (t *TreeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*TreeMux) ServeLookupResult

ServeLookupResult serves a request, given a lookup result from the Lookup function.

Jump to

Keyboard shortcuts

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