muxie

package module
v1.0.11 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2020 License: MIT Imports: 13 Imported by: 0

README

Muxie

:steam_locomotive::train::train::train::train::train:
Fast trie implementation designed from scratch specifically for HTTP
A small and light router for creating sturdy backend Go applications. Production-level tested, muxie's capabilities live inside the well-tested Iris web framework.

The little router that could. Built with ❤︎ by Gerasimos Maropoulos

Benchmark chart between muxie, httprouter, gin, gorilla mux, echo, vestigo and chi FOSSA Status

Last updated on October 17, 2018. Click here to read more details.

Features

  • trie based: performance and useness are first class citizens, Muxie is based on the prefix tree data structure, designed from scratch and built for HTTP, and it is among the fastest outhere, if not the fastest one
  • grouping: group common routes based on their path prefixes
  • no external dependencies: weighing 30kb, Muxie is a tiny little library without external dependencies
  • closest wildcard resolution and prefix-based custom 404: wildcards, named parameters and static paths can all live and play together nice and fast in the same path prefix or suffix(!)
  • small api: with only 3 main methods for HTTP there's not much to learn
  • compatibility: built to be 100% compatible with the net/http standard package

Technical Features

  • Closest Wildcard Resolution and Root wildcard (CWR)*
  • Parameterized Dynamic Path (named parameters with :name and wildcards with *name, can play all together for the same path prefix|suffix)*
  • Standard handlers chain (Pre(handlers).For(mainHandler) for individual routes and Mux#Use for router)*
  • Register handlers by method(s) (muxie.Methods())*
  • Register handlers by filters (Mux#HandleRequest and Mux#AddRequestHandler for muxie.Matcher and muxie.RequestHandler)
  • Handle subdomains with ease (muxie.Host Matcher)*
  • Request Processors (muxie.Bind and muxie.Dispatch)*

Interested? Want to learn more about this library? Check out our tiny examples and the simple godocs page.

Installation

The only requirement is the Go Programming Language

$ go get -u github.com/kataras/muxie

License

MIT

FOSSA Status

Documentation

Index

Constants

View Source
const (
	// ParamStart is the character, as a string, which a path pattern starts to define its named parameter.
	ParamStart = ":"
	// WildcardParamStart is the character, as a string, which a path pattern starts to define its named parameter for wildcards.
	// It allows everything else after that path prefix
	// but the Trie checks for static paths and named parameters before that in order to support everything that other implementations do not,
	// and if nothing else found then it tries to find the closest wildcard path(super and unique).
	WildcardParamStart = "*"
)

Variables

View Source
var (
	// Charset is the default content type charset for Request Processors .
	Charset = "utf-8"

	// JSON implements the full `Processor` interface.
	// It is responsible to dispatch JSON results to the client and to read JSON
	// data from the request body.
	//
	// Usage:
	// To read from a request:
	// muxie.Bind(r, muxie.JSON, &myStructValue)
	// To send a response:
	// muxie.Dispatch(w, muxie.JSON, mySendDataValue)
	JSON = &jsonProcessor{Prefix: nil, Indent: "", UnescapeHTML: false}

	// XML implements the full `Processor` interface.
	// It is responsible to dispatch XML results to the client and to read XML
	// data from the request body.
	//
	// Usage:
	// To read from a request:
	// muxie.Bind(r, muxie.XML, &myStructValue)
	// To send a response:
	// muxie.Dispatch(w, muxie.XML, mySendDataValue)
	XML = &xmlProcessor{Indent: ""}
)
View Source
var DefaultKeysSorter = func(list []string) func(i, j int) bool {
	return func(i, j int) bool {
		return len(strings.Split(list[i], pathSep)) < len(strings.Split(list[j], pathSep))
	}
}

DefaultKeysSorter sorts as: first the "key (the path)" with the lowest number of slashes.

View Source
var NoContentHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNoContent)
})

NoContentHandler defaults to a handler which just sends 204 status. See `MethodHandler.NoContent` method.

Functions

func Bind

func Bind(r *http.Request, b Binder, ptrOut interface{}) error

Bind accepts the current request and any `Binder` to bind the request data to the "ptrOut".

func Dispatch

func Dispatch(w http.ResponseWriter, d Dispatcher, v interface{}) error

Dispatch accepts the current response writer and any `Dispatcher` to send the "v" to the client.

func GetParam

func GetParam(w http.ResponseWriter, key string) string

GetParam returns the path parameter value based on its key, i.e "/hello/:name", the parameter key is the "name". For example if a route with pattern of "/hello/:name" is inserted to the `Trie` or handlded by the `Mux` and the path "/hello/kataras" is requested through the `Mux#ServeHTTP -> Trie#Search` then the `GetParam("name")` will return the value of "kataras". If not associated value with that key is found then it will return an empty string.

The function will do its job only if the given "w" http.ResponseWriter interface is an `ResponseWriter`.

func SetParam

func SetParam(w http.ResponseWriter, key, value string) bool

SetParam sets manually a parameter to the "w" http.ResponseWriter which should be a ResponseWriter. This is not commonly used by the end-developers, unless sharing values(string messages only) between handlers is absolutely necessary.

func TypeByExtension

func TypeByExtension(ext string) (typ string)

TypeByExtension returns the MIME type associated with the file extension ext. The extension ext should begin with a leading dot, as in ".html". When ext has no associated type, typeByExtension returns "".

Extensions are looked up first case-sensitively, then case-insensitively.

The built-in table is small but on unix it is augmented by the local system's mime.types file(s) if available under one or more of these names:

/etc/mime.types
/etc/apache2/mime.types
/etc/apache/mime.types

On Windows, MIME types are extracted from the registry.

Text types have the charset parameter set to "utf-8" by default.

func TypeByFilename

func TypeByFilename(fullFilename string) string

TypeByFilename same as TypeByExtension but receives a filename path instead.

Types

type Binder

type Binder interface {
	Bind(*http.Request, interface{}) error
}

Binder is the interface which `muxie.Bind` expects. It is used to bind a request to a go struct value (ptr).

type Dispatcher

type Dispatcher interface {
	// no io.Writer because we need to set the headers here,
	// Binder and Processor are only for HTTP.
	Dispatch(http.ResponseWriter, interface{}) error
}

Dispatcher is the interface which `muxie.Dispatch` expects. It is used to send a response based on a go struct value.

type Host

type Host string

Host is a Matcher for hostlines. It can accept exact hosts line like "mysubdomain.localhost:8080" or a suffix, i.e ".localhost:8080" will work as a wildcard subdomain for our root domain. The domain and the port should match exactly the request's data.

func (Host) Match

func (h Host) Match(r *http.Request) bool

Match validates the host, implementing the `Matcher` interface.

type InsertOption

type InsertOption func(*Node)

InsertOption is just a function which accepts a pointer to a Node which can alt its `Handler`, `Tag` and `Data` fields.

See `WithHandler`, `WithTag` and `WithData`.

func WithData

func WithData(data interface{}) InsertOption

WithData sets the node's optionally `Data` field.

func WithHandler

func WithHandler(handler http.Handler) InsertOption

WithHandler sets the node's `Handler` field (useful for HTTP).

func WithTag

func WithTag(tag string) InsertOption

WithTag sets the node's `Tag` field (may be useful for HTTP).

type Matcher

type Matcher interface {
	Match(*http.Request) bool
}

Matcher is the interface that all Matchers should be implemented in order to be registered into the Mux via the `Mux#AddRequestHandler/Match/MatchFunc` functions.

Look the `Mux#AddRequestHandler` for more.

type MatcherFunc

type MatcherFunc func(*http.Request) bool

MatcherFunc is a shortcut of the Matcher, as a function. See `Matcher`.

func (MatcherFunc) Match

func (fn MatcherFunc) Match(r *http.Request) bool

Match returns the result of the "fn" matcher. Implementing the `Matcher` interface.

type MethodHandler

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

MethodHandler implements the `http.Handler` which can be used on `Mux#Handle/HandleFunc` to declare handlers responsible for specific HTTP method(s).

Look `Handle` and `HandleFunc`.

func Methods

func Methods() *MethodHandler

Methods returns a MethodHandler which caller can use to register handler for specific HTTP Methods inside the `Mux#Handle/HandleFunc`. Usage: mux := muxie.NewMux() mux.Handle("/user/:id", muxie.Methods().

Handle("GET", getUserHandler).
Handle("POST", saveUserHandler))

func (*MethodHandler) Handle

func (m *MethodHandler) Handle(method string, handler http.Handler) *MethodHandler

Handle adds a handler to be responsible for a specific HTTP Method. Returns this MethodHandler for further calls. Usage: Handle("GET", myGetHandler).HandleFunc("DELETE", func(w http.ResponseWriter, r *http.Request){[...]}) Handle("POST, PUT", saveOrUpdateHandler)

^ can accept many methods for the same handler
^ methods should be separated by comma, comma following by a space or just space

func (*MethodHandler) HandleFunc

func (m *MethodHandler) HandleFunc(method string, handlerFunc func(w http.ResponseWriter, r *http.Request)) *MethodHandler

HandleFunc adds a handler function to be responsible for a specific HTTP Method. Returns this MethodHandler for further calls.

func (*MethodHandler) NoContent

func (m *MethodHandler) NoContent(methods ...string) *MethodHandler

NoContent registers a handler to a method which sends 204 (no status content) to the client.

Example: _examples/11_cors for more.

func (*MethodHandler) ServeHTTP

func (m *MethodHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Mux

type Mux struct {
	// PathCorrection removes leading slashes from the request path.
	// Defaults to false, however is highly recommended to turn it on.
	PathCorrection bool
	// PathCorrectionNoRedirect if `PathCorrection` is set to true,
	// it will execute the handlers chain without redirection.
	// Defaults to false.
	PathCorrectionNoRedirect bool
	Routes                   *Trie
	// contains filtered or unexported fields
}

Mux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered nodes and calls the handler for the pattern that most closely matches the URL.

Patterns name fixed, rooted paths and dynamic like /profile/:name or /profile/:name/friends or even /files/*file when ":name" and "*file" are the named parameters and wildcard parameters respectfully.

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/*myparam" matches all paths not matched by other registered patterns, but not the URL with Path == "/", for that you would need the pattern "/".

See `NewMux`.

func NewMux

func NewMux() *Mux

NewMux returns a new HTTP multiplexer which uses a fast, if not the fastest implementation of the trie data structure that is designed especially for path segments.

func (*Mux) AbsPath

func (m *Mux) AbsPath() string

AbsPath returns the absolute path of the router for this Mux group.

func (*Mux) AddRequestHandler

func (m *Mux) AddRequestHandler(requestHandler RequestHandler)

AddRequestHandler adds a full `RequestHandler` which is responsible to check if a handler should be executed via its `Matcher`, if the handler is executed then the router stops searching for this Mux' routes, RequestHandelrs have priority over the routes and the middlewares.

The "requestHandler"'s Handler can be any http.Handler and a new `muxie.NewMux` as well. The new Mux will be not linked to this Mux by-default, if you want to share middlewares then you have to use the `muxie.Pre` to declare the shared middlewares and register them via the `Mux#Use` function.

func (*Mux) Handle

func (m *Mux) Handle(pattern string, handler http.Handler)

Handle registers a route handler for a path pattern.

func (*Mux) HandleFunc

func (m *Mux) HandleFunc(pattern string, handlerFunc func(http.ResponseWriter, *http.Request))

HandleFunc registers a route handler function for a path pattern.

func (*Mux) HandleRequest

func (m *Mux) HandleRequest(matcher Matcher, handler http.Handler)

HandleRequest adds a matcher and a (conditional) handler to be executed when "matcher" passed. If the "matcher" passed then the "handler" will be executed and this Mux' routes will be ignored.

Look the `Mux#AddRequestHandler` for further details.

func (*Mux) Of

func (m *Mux) Of(prefix string) SubMux

Of returns a new Mux which its Handle and HandleFunc will register the path based on given "prefix", i.e: mux := NewMux() v1 := mux.Of("/v1") v1.HandleFunc("/users", myHandler) The above will register the "myHandler" to the "/v1/users" path pattern.

func (*Mux) ServeHTTP

func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP exposes and serves the registered routes.

func (m *Mux) Unlink() SubMux

Unlink will remove any inheritance fields from the parent mux (and its parent) that are inherited with the `Of` function. Returns the current SubMux. Usage:

mux := NewMux() mux.Use(myLoggerMiddleware) v1 := mux.Of("/v1").Unlink() // v1 will no longer have the "myLoggerMiddleware" or any Matchers. v1.HandleFunc("/users", myHandler)

func (*Mux) Use

func (m *Mux) Use(middlewares ...Wrapper)

Use adds middleware that should be called before each mux route's main handler. Should be called before `Handle/HandleFunc`. Order matters.

A Wrapper is just a type of `func(http.Handler) http.Handler` which is a common type definition for net/http middlewares.

To add a middleware for a specific route and not in the whole mux use the `Handle/HandleFunc` with the package-level `muxie.Pre` function instead. Functionality of `Use` is pretty self-explained but new gophers should take a look of the examples for further details.

type Node

type Node struct {

	// insert main data relative to http and a tag for things like route names.
	Handler http.Handler
	Tag     string

	// other insert data.
	Data interface{}
	// contains filtered or unexported fields
}

Node is the trie's node which path patterns with their data like an HTTP handler are saved to. See `Trie` too.

func NewNode

func NewNode() *Node

NewNode returns a new, empty, Node.

func (*Node) IsEnd

func (n *Node) IsEnd() bool

IsEnd returns true if this Node is a final path, has a key.

func (*Node) Keys

func (n *Node) Keys(sorter NodeKeysSorter) (list []string)

Keys returns this node's key (if it's a final path segment) and its children's node's key. The "sorter" can be optionally used to sort the result.

func (*Node) Parent

func (n *Node) Parent() *Node

Parent returns the parent of that node, can return nil if this is the root node.

func (*Node) String

func (n *Node) String() string

String returns the key, which is the path pattern for the HTTP Mux.

type NodeKeysSorter

type NodeKeysSorter = func(list []string) func(i, j int) bool

NodeKeysSorter is the type definition for the sorting logic that caller can pass on `GetKeys` and `Autocomplete`.

type ParamEntry

type ParamEntry struct {
	Key   string
	Value string
}

ParamEntry holds the Key and the Value of a named path parameter.

func GetParams

func GetParams(w http.ResponseWriter) []ParamEntry

GetParams returns all the available parameters based on the "w" http.ResponseWriter which should be a ResponseWriter.

The function will do its job only if the given "w" http.ResponseWriter interface is an `ResponseWriter`.

type ParamsSetter

type ParamsSetter interface {
	Set(string, string)
}

ParamsSetter is the interface which should be implemented by the params writer for `Search` in order to store the found named path parameters, if any.

type Processor

type Processor interface {
	Binder
	Dispatcher
}

Processor implements both `Binder` and `Dispatcher` interfaces. It is used for implementations that can `Bind` and `Dispatch` the same data form.

Look `JSON` and `XML` for more.

type RequestHandler

type RequestHandler interface {
	http.Handler
	Matcher
}

RequestHandler is the matcher and handler link interface. It is used inside the `Mux` to handle requests based on end-developer's custom logic. If a "Matcher" passed then the "Handler" is executing and the rest of the Mux' routes will be ignored.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	ParamsSetter
	Get(string) string
	GetAll() []ParamEntry
}

ResponseWriter is the muxie's specific ResponseWriter to hold the path parameters. Usage: use this to cast a handler's `http.ResponseWriter` and pass it as an embedded parameter to custom response writer that will be passed to the next handler in the chain.

type SubMux

type SubMux interface {
	Of(prefix string) SubMux
	Unlink() SubMux
	Use(middlewares ...Wrapper)
	Handle(pattern string, handler http.Handler)
	HandleFunc(pattern string, handlerFunc func(http.ResponseWriter, *http.Request))
	AbsPath() string
}

SubMux is the child of a main Mux.

type Trie

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

Trie contains the main logic for adding and searching nodes for path segments. It supports wildcard and named path parameters. Trie supports very coblex and useful path patterns for routes. The Trie checks for static paths(path without : or *) and named parameters before that in order to support everything that other implementations do not, and if nothing else found then it tries to find the closest wildcard path(super and unique).

func NewTrie

func NewTrie() *Trie

NewTrie returns a new, empty Trie. It is only useful for end-developers that want to design their own mux/router based on my trie implementation.

See `Trie`

func (*Trie) Autocomplete

func (t *Trie) Autocomplete(prefix string, sorter NodeKeysSorter) (list []string)

Autocomplete returns the keys that starts with "prefix", this is useful for custom search-engines built on top of my trie implementation.

func (*Trie) HasPrefix

func (t *Trie) HasPrefix(prefix string) bool

HasPrefix returns true if "prefix" is found inside the registered nodes.

func (*Trie) Insert

func (t *Trie) Insert(pattern string, options ...InsertOption)

Insert adds a node to the trie.

func (*Trie) Parents

func (t *Trie) Parents(prefix string) (parents []*Node)

Parents returns the list of nodes that a node with "prefix" key belongs to.

func (*Trie) Search

func (t *Trie) Search(q string, params ParamsSetter) *Node

Search is the most important part of the Trie. It will try to find the responsible node for a specific query (or a request path for HTTP endpoints).

Search supports searching for static paths(path without : or *) and paths that contain named parameters or wildcards. Priority as: 1. static paths 2. named parameters with ":" 3. wildcards 4. closest wildcard if not found, if any 5. root wildcard

func (*Trie) SearchPrefix

func (t *Trie) SearchPrefix(prefix string) *Node

SearchPrefix returns the last node which holds the key which starts with "prefix".

type Wrapper

type Wrapper func(http.Handler) http.Handler

Wrapper is just a type of `func(http.Handler) http.Handler` which is a common type definition for net/http middlewares.

type Wrappers

type Wrappers []Wrapper

Wrappers contains `Wrapper`s that can be registered and used by a "main route handler". Look the `Pre` and `For/ForFunc` functions too.

func Pre

func Pre(middleware ...Wrapper) Wrappers

Pre starts a chain of handlers for wrapping a "main route handler" the registered "middleware" will run before the main handler(see `Wrappers#For/ForFunc`).

Usage: mux := muxie.NewMux() myMiddlewares := muxie.Pre(myFirstMiddleware, mySecondMiddleware) mux.Handle("/", myMiddlewares.ForFunc(myMainRouteHandler))

func (Wrappers) For

func (w Wrappers) For(main http.Handler) http.Handler

For registers the wrappers for a specific handler and returns a handler that can be passed via the `Handle` function.

func (Wrappers) ForFunc

func (w Wrappers) ForFunc(mainFunc func(http.ResponseWriter, *http.Request)) http.Handler

ForFunc registers the wrappers for a specific raw handler function and returns a handler that can be passed via the `Handle` function.

Directories

Path Synopsis
_benchmarks
chi
gin
_examples
6_middleware
Package main will explore the helpers for middleware(s) that Muxie has to offer, but they are totally optional, you can still use your favourite pattern to wrap route handlers.
Package main will explore the helpers for middleware(s) that Muxie has to offer, but they are totally optional, you can still use your favourite pattern to wrap route handlers.

Jump to

Keyboard shortcuts

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