router

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2021 License: Apache-2.0 Imports: 10 Imported by: 0

README

Router

aws apigateway lambda router for golang

Example:

package main

import (
	"context"
	"encoding/json"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/werbenhu/router"
)

var r *router.Router

func init() {
	r = router.New()
	r.Get("/test", test)
	r.Get("/test/:name", testWithName)
}

func testWithName(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	name := request.QueryStringParameters[":name"]
	resp := map[string]interface{}{
		"name":   name,
		"path":   request.Path,
		"method": request.HTTPMethod,
		"params": request.QueryStringParameters,
	}

	body, _ := json.Marshal(resp)
	return events.APIGatewayProxyResponse{Body: string(body), StatusCode: 200}, nil
}

func test(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	resp := map[string]interface{}{
		"path":   request.Path,
		"method": request.HTTPMethod,
		"params": request.QueryStringParameters,
	}

	body, _ := json.Marshal(resp)
	return events.APIGatewayProxyResponse{Body: string(body), StatusCode: 200}, nil
}

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

Documentation

Overview

Package mux implements a high performance and powerful trie based url path router for Go.

Index

Constants

View Source
const Version = "0.0.1"

Version holds the current mux version

Variables

View Source
var ExposeServerErrors = true

Functions

func Delete added in v1.0.2

func Delete(pattern string, handler HandlerFunc)

func Get added in v1.0.2

func Get(pattern string, handler HandlerFunc)

func HandleError

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

func Handler added in v1.0.2

func Head(pattern string, handler HandlerFunc)

func MarshalResponse

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

func Options

func Options(pattern string, handler HandlerFunc)

func Param

func Param(r *http.Request, key string) string

Param return the router param based on the key

func Params

func Params(r *http.Request) map[string]string

Params return the router params

func Patch added in v1.0.2

func Patch(pattern string, handler HandlerFunc)

func Post added in v1.0.2

func Post(pattern string, handler HandlerFunc)

func Put added in v1.0.2

func Put(pattern string, handler HandlerFunc)

Types

type Group added in v1.0.2

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

func NewGroup added in v1.0.2

func NewGroup(name string) *Group

func (*Group) Delete added in v1.0.2

func (g *Group) Delete(pattern string, handler HandlerFunc)

func (*Group) Get added in v1.0.2

func (g *Group) Get(pattern string, handler HandlerFunc)

func (*Group) Head added in v1.0.2

func (g *Group) Head(pattern string, handler HandlerFunc)

func (*Group) Options added in v1.0.2

func (g *Group) Options(pattern string, handler HandlerFunc)

func (*Group) Patch added in v1.0.2

func (g *Group) Patch(pattern string, handler HandlerFunc)

func (*Group) Post added in v1.0.2

func (g *Group) Post(pattern string, handler HandlerFunc)

func (*Group) Put added in v1.0.2

func (g *Group) Put(pattern string, handler HandlerFunc)

type Matched

type Matched struct {
	// Either a Node pointer when matched or nil
	Node *Node

	// Either a map contained matched values or empty map.
	Params map[string]string

	// Matched path to access
	// If Node is nil then redirect to this PATH
	Path string
}

Matched is a result returned by Trie.Match.

type Node

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

Node represents a node on defined patterns that can be matched.

func (*Node) BuildURL

func (n *Node) BuildURL(pairs ...string) (*url.URL, error)

BuildURL will builds a URL for the pattern.

func (*Node) GetAllow

func (n *Node) GetAllow() []string

GetAllow returns allow methods defined on the node

trie := New()
trie.Parse("/").Handle("GET", handler1)
trie.Parse("/").Handle("PUT", handler2)

// trie.Match("/").Node.GetAllow() == []string{"GET", "PUT"}

func (*Node) GetHandler

func (n *Node) GetHandler(method string) interface{}

GetHandler ... GetHandler returns handler by method that defined on the node

trie := New()
trie.Parse("/api").Handle("GET", func handler1() {})
trie.Parse("/api").Handle("PUT", func handler2() {})

trie.Match("/api").Node.GetHandler("GET").(func()) == handler1
trie.Match("/api").Node.GetHandler("PUT").(func()) == handler2

func (*Node) GetName

func (n *Node) GetName(name string) *Node

GetName returns the name for the route, if any.

func (*Node) Handle

func (n *Node) Handle(method string, handler interface{})

Handle is used to mount a handler with a method name to the node.

t := New()
node := t.Define("/a/b")
node.Handle("GET", handler1)
node.Handle("POST", handler1)

func (*Node) Name

func (n *Node) Name(name string) *Node

Name sets the name for the route, used to build URLs.

type Router

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

Mux is a tire base HTTP request router which can be used to dispatch requests to different handler functions.

func New

func New(opts ...TOptions) *Router

New returns a Mux instance.

func (*Router) DefaultHandler

func (r *Router) DefaultHandler(handler HandlerFunc)

DefaultHandler registers a new handler in the Mux that will run if there is no other handler matching.

func (*Router) Delete

func (r *Router) Delete(pattern string, handler HandlerFunc)

Delete registers a new DELETE route for a path with matching handler in the Mux.

func (*Router) Get

func (r *Router) Get(pattern string, handler HandlerFunc)

Get registers a new GET route for a path with matching handler in the Mux.

func (*Router) Handle

func (r *Router) Handle(method, pattern string, handler HandlerFunc)

Handle registers a new handler with method and path in the Mux. For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

func (*Router) Handler

ServeHTTP implemented http.Handler interface

func (*Router) Head

func (r *Router) Head(pattern string, handler HandlerFunc)

Head registers a new HEAD route for a path with matching handler in the Mux.

func (*Router) Options

func (r *Router) Options(pattern string, handler HandlerFunc)

Options registers a new OPTIONS route for a path with matching handler in the Mux.

func (*Router) Patch

func (r *Router) Patch(pattern string, handler HandlerFunc)

Patch registers a new PATCH route for a path with matching handler in the Mux.

func (*Router) Post

func (r *Router) Post(pattern string, handler HandlerFunc)

Post registers a new POST route for a path with matching handler in the Mux.

func (*Router) Put

func (r *Router) Put(pattern string, handler HandlerFunc)

Put registers a new PUT route for a path with matching handler in the Mux.

type RouterError

type RouterError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (RouterError) Error

func (err RouterError) Error() string

type TOptions added in v1.0.2

type TOptions struct {
	// CaseSensitive when matching URL path.
	CaseSensitive bool

	// PathClean defines the path cleaning behavior for new routes. The default value is false.
	// Users should be careful about which routes are not cleaned
	// When true, the path will be cleaned, if the route path is "/path//to", it will return "/path/to"
	// When false, if the route path is "/path//to", it will remain with the double slash
	PathClean bool

	// 	StrictSlash defines the trailing slash behavior for new routes.
	// The initial value is false.
	// When true, if the route path is "/path/", accessing "/path" will
	//    redirect to the former and vice versa. In other words,
	//    your application will always see the path as specified in the route.
	// When false, if the route path is "/path", accessing "/path/" will
	//    not match this route and vice versa.
	StrictSlash bool

	// UseEncodedPath tells the router to match the encoded original path to the routes.
	// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
	// This behavior has the drawback of needing to match routes against r.RequestURI instead of r.URL.Path.
	// Any modifications (such as http.StripPrefix) to r.URL.Path will not affect routing when this flag is
	// on and thus may induce unintended behavior.
	// If not called, the router will match the unencoded path to the routes.
	// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
	UseEncodedPath bool
}

Options describes options for Trie.

type Trie

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

Trie represents a trie that defining patterns and matching URL.

func NewTrie

func NewTrie(args ...TOptions) *Trie

NewTrie returns a trie

trie := New()
// disable CaseSensitive, PathClean and StrictSlash
trie := New(Options{})

func (*Trie) Match

func (t *Trie) Match(path string) (*Matched, error)

Match try to match path. It will returns a Matched instance that includes *Node, Params when matching success, otherwise a nil.

matched, err := trie.Match("/a/b")

func (*Trie) Parse

func (t *Trie) Parse(pattern string) *Node

Parse will parse the pattern and returns the endpoint node for the pattern.

trie := New()
node1 := trie.Parse("/a")
node2 := trie.Parse("/a/b")
node3 := trie.Parse("/a/b")
// node2.parent == node1
// node2 == node3

Jump to

Keyboard shortcuts

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