mux

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2021 License: MPL-2.0 Imports: 7 Imported by: 3

README

Package sharpvik/mux

This package seeks to provide customizable and convenient internal routing for Go's http.Server.

When building a server-side app or a REST API, you may wish to implement complex routing mechanisms that allow you to effectively process incoming requests by checking its signature against different routes with preset filters.

There already exist a few packages that provide this functionality. However, there is a catch: those packages are written as though the only things your handler functions are going to be working with are http.ResponseWriter and http.Request sent by the user. In reality, you may wish to query a database and/or log some data through log.Logger. Of course, there are ways to allow function to acces those interfaces via a global variable or something like that, but those are a pain to write tests for.

In this package, you can find the Router sturct that is written in a way that resolves those problems by supporting the router-embedded context.

Theory

Mux allows you to build flexible and fairly complex routing schemas by giving you the Router. To create new Router you should use the New function.

func New() *Router

Having a single Router may be exactly what you want, but it is unlikely that you decided to use this package for such basic use case. The cool things come when you make more Routers! Or, to be more precise, more Subrouters.

func (rtr *Router) Subrouter() *Router

License

Use of this source code is governed by the Mozilla Public License Version 2.0 that can be found in the LICENSE file.

Documentation

Overview

Package mux seeks to provide customizable and convenient internal routing for Go's http.Server.

When building a server-side app or a REST API, you may wish to implement complex routing mechanisms that allow you to effectively process incoming requests by checking their signatures against different routes with preset filters.

There already exist a few packages that provide this functionality. However, there is a catch: those packages are written as though the only things your handler functions are going to be working with are http.ResponseWriter and http.Request sent by the user. In reality, you may wish to query a database and/or log some data through log.Logger. Of course, there are ways to allow a function to acces those interfaces via a global variable or something like that, but those ways are a pain to write tests for.

In this package, you can find the Router sturct that is written in a way that resolves those problems by supporting the router-embedded context.

Index

Constants

This section is empty.

Variables

View Source
var DefaultFailHandler = http.NotFoundHandler()

DefaultFailHandler is a default handler attached to every Router. Use Router.Fail to specify a custom one.

Functions

func Vars

func Vars(r *http.Request) (varsmap map[string]interface{}, ok bool)

Vars function returns path variables in a map[string]interface{} and a boolean success confirmation flag.

Types

type Filter

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

Filter is an interface type that represents functionality of a filter.

type Filters

type Filters struct {
	Schemes    *SchemesFilter    // e.g. "http" or "https".
	Methods    *MethodsFilter    // e.g. "GET", "POST", "PUT", "DELETE", etc.
	Path       *PathFilter       // e.g. "/home" or "/r/{sub:str}/{id:int}".
	PathPrefix *PathPrefixFilter // e.g. "/api".
}

Filters is a concrete type that contains fields for every possible filter allowed on a Router. It ensures that only one filter of each type is used per Router instance.

func NewFilters

func NewFilters() *Filters

NewFilters returns pointer to an empty set of filters.

func (*Filters) Match

func (fils *Filters) Match(r *http.Request) bool

Match method returns boolean value that tells you whether given request passed all the filters. Also, *Filters implements the Filter interface since it has this method.

type MethodsFilter

type MethodsFilter struct {
	Methods set
}

MethodsFilter takes care of filtering requests by method (e.g. "POST"). If you would like to see all the request methods that exist, go here:

https://golang.org/pkg/net/http/#pkg-constants

It is advized that you use Go's standard "net/http" package in order to manage these. For example:

package main

import (
    "net/http"
    "github.com/sharpvik/mux"
)

func main() {
    // Create new filter instance using a constant from "net/http".
    filter := mux.NewMethodsFilter(http.MethodPost)

    // Add method "GET" to filter's Methods.
    filter.Methods.Add(http.MethodGet)
}

func NewMethodsFilter

func NewMethodsFilter(methods ...string) *MethodsFilter

NewMethodsFilter function returns pointer to a custom MethodsFilter.

func (MethodsFilter) Match

func (fil MethodsFilter) Match(r *http.Request) bool

Match method returns boolean value that tells you whether given request passed the filter. Also, *MethodsFilter implements the Filter interface since it has this method.

type PathFilter

type PathFilter struct {
	// Path is a pattern string that is used to compose and compile a proper
	// regual expression (Regexp) that will be used to match URL paths.
	Path string

	// Regexp is a compiled regular expression that is created by the
	// NewPathFilter function; it is going to be used to check if request path
	// matches the PathFilter.
	Regexp *regexp.Regexp
	// contains filtered or unexported fields
}

PathFilter takes care of filtering requests by their URL path (e.g. "/api").

func NewPathFilter

func NewPathFilter(path string) *PathFilter

NewPathFilter returns pointer to a newly created PathFilter. It also ensures that the first character in the uri is a forward-slash -- if it isn't there, it will be inserted.

func (*PathFilter) Match

func (fil *PathFilter) Match(r *http.Request) bool

Match method returns boolean value that tells you whether given request passed the filter. Also, *PathFilter implements the Filter interface since it has this method.

type PathPrefixFilter

type PathPrefixFilter string

PathPrefixFilter takes care of filtering requests by URL path prefix. It is an alias to the standard string type. The string it wraps is the aforementioned path prefix which we wish to utilize for route matching purposes.

func NewPathPrefixFilter

func NewPathPrefixFilter(prefix string) *PathPrefixFilter

NewPathPrefixFilter returns reference to a newly created PathPrefixFilter.

func (*PathPrefixFilter) Match

func (fil *PathPrefixFilter) Match(r *http.Request) bool

Match method uses the string (that PathPrefixFilter wraps around) to decide whether the request in question matches or not.

type Router

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

Router represents the node of a routing tree.

func New

func New() *Router

New is a constructor used to create the root of a routing tree. Root doesn't need any filters as it is invoked automatically by the server anyway. The routes will be added later, using Router's methods.

func (*Router) Fail

func (rtr *Router) Fail(handler http.Handler) *Router

Fail method sets router's fail message.

func (*Router) FailFunc added in v0.2.0

func (rtr *Router) FailFunc(v View) *Router

FailFunc method sets router's fail message.

func (*Router) HandleFunc

func (rtr *Router) HandleFunc(v View) *Router

HandleFunc method sets router's handler to a function.

func (*Router) Handler

func (rtr *Router) Handler(h http.Handler) *Router

Handler method sets router's handler.

func (*Router) Match

func (rtr *Router) Match(r *http.Request) (sub *Router, match bool)

Match method must go through all registered routes one by one and check if their filters match the request. It returns the first sub-router where filters matched and a boolean value indicating that there was a match. If there was no match, it returns nil as the sub-router while setting the second value to false.

func (*Router) Methods

func (rtr *Router) Methods(methods ...string) *Router

Methods returns pointer to the same Router instance while altering its methods filter.

NOTICE: If methods filter has already been set for this Router instance, it will get replaced!

func (*Router) Path

func (rtr *Router) Path(path string) *Router

Path returns pointer to the same Router instance while altering its path filter.

NOTICE: This method replaces router's PathFilter with a newly created instance while setting PathPrefix to nil.

func (*Router) PathPrefix

func (rtr *Router) PathPrefix(prefix string) *Router

PathPrefix returns pointer to the same Router instance while altering its path prefix filter.

NOTICE: This method replaces router's PathPrefixFilter with a newly created instance while setting PathFilter to nil.

func (*Router) Schemes

func (rtr *Router) Schemes(schemes ...string) *Router

Schemes returns pointer to the same Router instance while altering its schemes filter.

NOTICE: This method replaces router's SchemesFilter with a newly created instance.

func (*Router) ServeHTTP

func (rtr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP method is here in order to ensure that Router implements the http.Handler interface. It is invoked automatically by http.Server if you assign Router in question as server's Handler. If this Router is not root, but a sub-router instead, its ServeHTTP method will be invoked by the parent Router whenever some request passes all its filters upon checkup.

func (*Router) Subrouter

func (rtr *Router) Subrouter() *Router

Subrouter method returns pointer to a new sub-router instance that inherits context from its parent.

func (*Router) Use added in v0.2.0

func (rtr *Router) Use(h http.Handler) *Router

Use registers a middleware handler on the Router.

func (*Router) UseFunc added in v0.2.0

func (rtr *Router) UseFunc(v View) *Router

Use registers a middleware View handler on the Router.

type SchemesFilter

type SchemesFilter struct {
	Schemes set
}

SchemesFilter takes care of filtering requests by scheme (e.g. "https").

func NewSchemesFilter

func NewSchemesFilter(schemes ...string) *SchemesFilter

NewSchemesFilter function returns pointer to a custom SchemesFilter.

func (*SchemesFilter) Match

func (fil *SchemesFilter) Match(r *http.Request) bool

Match method returns boolean value that tells you whether given request passed the filter. Also, *SchemesFilter implements the Filter interface since it has this method.

type View

type View func(http.ResponseWriter, *http.Request)

View represents the default handler function type.

func (View) ServeHTTP

func (v View) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP method ensures that View implements http.Handler interface.

Jump to

Keyboard shortcuts

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