httpub

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2021 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TwentyFourHours   = 86400
	FourthyEightHours = 2 * TwentyFourHours

	TwentyFourHoursDuration   = TwentyFourHours * time.Second
	FourthyEightHoursDuration = TwentyFourHoursDuration * 2
)

Time constants

View Source
const (
	CONNECT = "CONNECT"
	DELETE  = "DELETE"
	GET     = "GET"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	POST    = "POST"
	PUT     = "PUT"
	TRACE   = "TRACE"
)

HTTP methods

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-GroupProtocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-Id"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

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.

Functions

func Bind

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

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

func CreateBody

func CreateBody(jsn *njson.JSON) (bytes.Buffer, error)

CreateBody writes giving json content into the buffer.

func CreateError

func CreateError(err error, message string, code int) (bytes.Buffer, error)

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 IsWebSocket

func IsWebSocket(r *Request) bool

IsWebSocket returns true/false if the giving reqest is a websocket connection.

func Scheme

func Scheme(r *Request) string

Scheme attempts to return the exact url scheme of the request.

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

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(*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 BufferCloser

type BufferCloser struct {
	*bytes.Buffer
}

func NewBufferCloser

func NewBufferCloser(bw *bytes.Buffer) *BufferCloser

func (*BufferCloser) Close

func (bc *BufferCloser) Close() error

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 Handler

type Handler interface {
	Handle(req *Request, params sabuhp.Params) Response
}
var NoContentHandler Handler = HandlerFunc(func(r *Request, p sabuhp.Params) Response {
	var res Response
	res.Headers = sabuhp.Header{}
	res.Code = http.StatusNoContent
	return res
})

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

type HandlerFunc

type HandlerFunc func(req *Request, params sabuhp.Params) Response

func (HandlerFunc) Handle

func (h HandlerFunc) Handle(req *Request, params sabuhp.Params) Response

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 *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 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 MatchableContextHandler

type MatchableContextHandler interface {
	Match(error) bool
	Handle(r *Request, params sabuhp.Params) Response
}

MatchableContextHandler defines a condition which matches expected error for performing giving action.

func Matchable

func Matchable(err error, fn Handler) MatchableContextHandler

Matchable returns MatchableContextHandler using provided arguments.

func MatchableFunction

func MatchableFunction(err func(error) bool, fn Handler) MatchableContextHandler

MatchableFunction returns MatchableContextHandler using provided arguments.

type Matcher

type Matcher interface {
	Match(*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(*Request) bool

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

func (MatcherFunc) Match

func (fn MatcherFunc) Match(r *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 `Handler` which can be used on `Mux#UseHandle/UseHandleFunc` to declare handlers responsible for specific HTTP method(s).

Look `UseHandle` and `UseHandleFunc`.

func Methods

func Methods() *MethodHandler

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

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

func (*MethodHandler) Handle

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

Handle adds a handler to be responsible for a specific HTTP Method. Returns this MethodHandler for further calls. Usage: Handle("GET", myGetHandler).UseHandleFunc("DELETE", func(w http.ResponseWriter, r *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(r *Request, p sabuhp.Params) Response) *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(r *Request) Handler

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 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(r *Request) Response

Serve exposes and serves the registered routes.

func (*Mux) HandleRequest

func (m *Mux) HandleRequest(matcher Matcher, handler 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.UseHandleFunc("/users", myHandler) The above will register the "myHandler" to the "/v1/users" path pattern.

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.UseHandleFunc("/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 `UseHandle/UseHandleFunc`. Order matters.

A Wrapper is just a type of `func(Handler) 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 `UseHandle/UseHandleFunc` 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.

func (*Mux) UseHandle

func (m *Mux) UseHandle(pattern string, handler Handler)

Handle registers a route handler for a path pattern.

func (*Mux) UseHandleFunc

func (m *Mux) UseHandleFunc(pattern string, handlerFunc func(*Request, sabuhp.Params) Response)

HandleFunc registers a route handler function for a path pattern.

type Node

type Node struct {

	// insert main data relative to http and a tag for things like route names.
	Handler 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 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 Request

type Request struct {
	Proto            string // "HTTP/1.0"
	TransferEncoding []string
	Host             string
	Form             url.Values
	PostForm         url.Values
	MultipartForm    *multipart.Form
	IP               string
	TLS              bool
	Method           string
	URL              *url.URL
	Cookies          []sabuhp.Cookie
	Body             io.ReadCloser
	Headers          sabuhp.Header
	Conn             net.Conn
	Req              *http.Request
}

Request implements a underline carrier of a request object which will be used by a transport to request giving resource.

func HTTPRequestToRequest

func HTTPRequestToRequest(req *http.Request) *Request

func NewRequest

func NewRequest(addr string, method string, body io.ReadCloser) (*Request, error)

type RequestHandler

type RequestHandler interface {
	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 Response

type Response struct {
	// RedirectURL is used to indicate the url to redirect to
	// if we are doing a Temporary or Permanent redirect response.
	// It's usually should be null unless its a redirect.
	RedirectURL *url.URL

	// Code is the HTTP response code set by WriteHeader.
	//
	// Note that if a Handler never calls WriteHeader or Write,
	// this might end up being 0, rather than the implicit
	// http.StatusOK. To get the implicit value, use the Result
	// method.
	Code int

	// Headers the headers explicitly set by the Handler.
	Headers sabuhp.Header

	// Cookies contains the cookies to be written as part of response.
	Cookies []sabuhp.Cookie

	// Body is the buffer to which the Handler's Write calls are sent.
	// If nil, the Writes are silently discarded.
	Body io.WriteCloser

	// Flushed is whether the Handler called Flush.
	Flushed bool

	// Err object attached to response.
	Err error
}

Response is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

func NewResponse

func NewResponse(w io.WriteCloser) *Response

NewResponse returns an initialized Response.

func (*Response) Header

func (rw *Response) Header() map[string][]string

Header returns the response headers.

func (*Response) Write

func (rw *Response) Write(buf []byte) (int, error)

Write always succeeds and writes to rw.Body, if not nil.

func (*Response) WriteString

func (rw *Response) WriteString(str string) (int, error)

WriteString always succeeds and writes to rw.Body, if not nil.

type Service

type Service interface {
	Serve(w *Response, r *Request)
}

Service defines what we expect from a service server which is responsible for the handling of incoming requests for a giving service type and the response for that giving request.

type SubMux

type SubMux interface {
	Of(prefix string) SubMux
	Unlink() SubMux
	Use(middlewares ...Wrapper)
	UseHandle(pattern string, handler Handler)
	AbsPath() string
	UseHandleFunc(pattern string, handlerFunc func(*Request, sabuhp.Params) Response)
}

SubMux is the child of a main Mux.

type Transport

type Transport interface {
	Send(ctx context.Context, request *Request) (Response, error)
}

Transport defines what we expect from a handler of requests. It will be responsible for the serialization of request to server and delivery of response or error from server.

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(Handler) Handler

Wrapper is just a type of `func(Handler) 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.UseHandle("/", myMiddlewares.ForFunc(myMainRouteHandler))

func (Wrappers) For

func (w Wrappers) For(main Handler) Handler

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

func (Wrappers) ForFunc

func (w Wrappers) ForFunc(mainFunc func(*Request, sabuhp.Params) Response) Handler

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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