Documentation ¶
Index ¶
- Constants
- Variables
- func Bind(r *http.Request, b Binder, ptrOut interface{}) error
- func Dispatch(w http.ResponseWriter, d Dispatcher, v interface{}) error
- func GetParam(w http.ResponseWriter, key string) string
- func SetParam(w http.ResponseWriter, key, value string) bool
- func TypeByExtension(ext string) (typ string)
- func TypeByFilename(fullFilename string) string
- type Binder
- type Dispatcher
- type Host
- type InsertOption
- type Matcher
- type MatcherFunc
- type MethodHandler
- func (m *MethodHandler) Handle(method string, handler http.Handler) *MethodHandler
- func (m *MethodHandler) HandleFunc(method string, handlerFunc func(w http.ResponseWriter, r *http.Request)) *MethodHandler
- func (m *MethodHandler) NoContent(methods ...string) *MethodHandler
- func (m *MethodHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type Mux
- func (m *Mux) AbsPath() string
- func (m *Mux) AddRequestHandler(requestHandler RequestHandler)
- func (m *Mux) Handle(pattern string, handler http.Handler)
- func (m *Mux) HandleFunc(pattern string, handlerFunc func(http.ResponseWriter, *http.Request))
- func (m *Mux) HandleRequest(matcher Matcher, handler http.Handler)
- func (m *Mux) Of(prefix string) SubMux
- func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (m *Mux) Unlink() SubMux
- func (m *Mux) Use(middlewares ...Wrapper)
- type Node
- type NodeKeysSorter
- type ParamEntry
- type ParamsSetter
- type Processor
- type RequestHandler
- type ResponseWriter
- type SubMux
- type Trie
- func (t *Trie) Autocomplete(prefix string, sorter NodeKeysSorter) (list []string)
- func (t *Trie) HasPrefix(prefix string) bool
- func (t *Trie) Insert(pattern string, options ...InsertOption)
- func (t *Trie) Parents(prefix string) (parents []*Node)
- func (t *Trie) Search(q string, params ParamsSetter) *Node
- func (t *Trie) SearchPrefix(prefix string) *Node
- type Wrapper
- type Wrappers
Constants ¶
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 ¶
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: ""} )
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.
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 ¶
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 ¶
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 ¶
TypeByFilename same as TypeByExtension but receives a filename path instead.
Types ¶
type Binder ¶
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.
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 ¶
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 ¶
MatcherFunc is a shortcut of the Matcher, as a function. See `Matcher`.
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) 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) HandleFunc ¶
HandleFunc registers a route handler function for a path pattern.
func (*Mux) HandleRequest ¶
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 ¶
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 (*Mux) Unlink ¶
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 ¶
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 (*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.
type NodeKeysSorter ¶
NodeKeysSorter is the type definition for the sorting logic that caller can pass on `GetKeys` and `Autocomplete`.
type ParamEntry ¶
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 ¶
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 ¶
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) Insert ¶
func (t *Trie) Insert(pattern string, options ...InsertOption)
Insert adds a node to the trie.
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 ¶
SearchPrefix returns the last node which holds the key which starts with "prefix".
type Wrapper ¶
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 ¶
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))
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_benchmarks
|
|
_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. |