Documentation
¶
Overview ¶
Package gorilla/mux implements a request router and dispatcher.
The name mux stands for "HTTP request multiplexer". Like the standard http.ServeMux, mux.Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
- Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
- URL hosts and paths can have variables with an optional regular expression.
- Registered URLs can be built, or "reversed", which helps maintaining references to resources.
- Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
- It implements the http.Handler interface so it is compatible with the standard http.ServeMux.
Let's start registering a couple of URL paths and handlers:
func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) }
Here we register three routes mapping URL paths to handlers. This is equivalent to how http.HandleFunc() works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (http.ResponseWriter, *http.Request) as parameters.
Paths can have variables. They are defined using the format {name} or {name:pattern}. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
r := mux.NewRouter() r.HandleFunc("/products/{key}", ProductHandler) r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
The names are used to create a map of route variables which can be retrieved calling mux.Vars():
vars := mux.Vars(request) category := vars["category"]
And this is all you need to know about the basic usage. More advanced options are explained below.
Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
r := mux.NewRouter() // Only matches if domain is "www.domain.com". r.Host("www.domain.com") // Matches a dynamic subdomain. r.Host("{subdomain:[a-z]+}.domain.com")
There are several other matchers that can be added. To match path prefixes:
r.PathPrefix("/products/")
...or HTTP methods:
r.Methods("GET", "POST")
...or URL schemes:
r.Schemes("https")
...or header values:
r.Headers("X-Requested-With", "XMLHttpRequest")
...or query values:
r.Queries("key", "value")
...or to use a custom matcher function:
r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { return r.ProtoMajor == 0 })
...and finally, it is possible to combine several matchers in a single route:
r.HandleFunc("/products", ProductsHandler). Host("www.domain.com"). Methods("GET"). Schemes("http")
Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
For example, let's say we have several URLs that should only match when the host is "www.domain.com". Create a route for that host and get a "subrouter" from it:
r := mux.NewRouter() s := r.Host("www.domain.com").Subrouter()
Then register routes in the subrouter:
s.HandleFunc("/products/", ProductsHandler) s.HandleFunc("/products/{key}", ProductHandler) s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
The three URL paths we registered above will only be tested if the domain is "www.domain.com", because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
r := mux.NewRouter() s := r.PathPrefix("/products").Subrouter() // "/products/" s.HandleFunc("/", ProductsHandler) // "/products/{key}/" s.HandleFunc("/{key}/", ProductHandler) // "/products/{key}/details" s.HandleFunc("/{key}/details", ProductDetailsHandler)
Now let's see how to build registered URLs.
Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling Name() on a route. For example:
r := mux.NewRouter() r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). Name("article")
To build a URL, get the route and call the URL() method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
url, err := r.Get("article").URL("category", "technology", "id", "42")
...and the result will be a url.URL with the following path:
"/articles/technology/42"
This also works for host variables:
r := mux.NewRouter() r.Host("{subdomain}.domain.com"). Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") // url.String() will be "http://news.domain.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42")
All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
There's also a way to build only the URL host or path for a route: use the methods URLHost() or URLPath() instead. For the previous route, we would do:
// "http://news.domain.com/" host, err := r.Get("article").URLHost("subdomain", "news") // "/articles/technology/42" path, err := r.Get("article").URLPath("category", "technology", "id", "42")
And if you use subrouters, host and path defined separately can be built as well:
r := mux.NewRouter() s := r.Host("{subdomain}.domain.com").Subrouter() s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") // "http://news.domain.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42")
Index ¶
- Constants
- Variables
- func AddValueToParams(Name string, Value string, Type ParamType, From FromType, ps *Params) (k int)
- func ApacheLogingAfter(www *MidBuffer, req *http.Request, ps *Params) int
- func ApacheLogingBefore(www *MidBuffer, req *http.Request, ps *Params) int
- func DumpMatchItRan(x MatchItRankType) (rv string)
- func FixPath(pth string, rv []string, max int) int
- func FromTypeToString(ff FromType) string
- func GetCurTime() (s string)
- func InitMuxRouterProcessing(r *MuxRouter, trr *MuxRouterProcessing)
- func InitParams(p *Params)
- func IsMapStringBoolEmpty(v map[string]bool) bool
- func LastIndexOfChar(s string, ch uint8) int
- func LineFile(d ...int) (string, int)
- func MethodParam(www *MidBuffer, req *http.Request, ps *Params) int
- func MethodParamReg(www http.ResponseWriter, req *http.Request, ps *Params) int
- func MethodToCode(Method string, AddM int) int
- func OrderedBy(less ...lessFunc) *multiSorter
- func OrderedByPat(less ...lessFuncPat) *multiSorterPat
- func ParseBodyAsParams(www *MidBuffer, req *http.Request, ps *Params) int
- func ParseBodyAsParamsReg(www http.ResponseWriter, req *http.Request, ps *Params) int
- func ParseCookiesAsParams(www *MidBuffer, req *http.Request, ps *Params) int
- func ParseCookiesAsParamsReg(www http.ResponseWriter, req *http.Request, ps *Params) int
- func ParseQueryParams(www *MidBuffer, req *http.Request, ps *Params) int
- func ParseQueryParamsReg(www http.ResponseWriter, req *http.Request, ps *Params) int
- func PeekAtBody(req *http.Request) []byte
- func PrefixWith(www *MidBuffer, req *http.Request, ps *Params) int
- func RenameReservedItems(www http.ResponseWriter, req *http.Request, ps *Params, ri map[string]bool)
- func SVar(v interface{}) string
- func SVarI(v interface{}) string
- func ServeHTTP(fx func(w http.ResponseWriter, r *http.Request)) (rv func(res http.ResponseWriter, req *http.Request, ps Params))
- func SetCurTime(s string)
- func SetupUnsedParam(NormalUnused []UnusedParam)
- type ARoute
- func (r *ARoute) AppendFileName(p string) *ARoute
- func (r *ARoute) Comment(c string) *ARoute
- func (r *ARoute) HandleFunc(path string, f HandleFunc) *ARoute
- func (r *ARoute) Headers(pairs ...string) *ARoute
- func (r *ARoute) Host(h string) *ARoute
- func (r *ARoute) HostPort(h string) *ARoute
- func (r *ARoute) Id(n int) *ARoute
- func (r *ARoute) Methods(methods ...string) *ARoute
- func (r *ARoute) Name(n string) *ARoute
- func (r *ARoute) Path(p string) *ARoute
- func (r *ARoute) PathPrefix(p string) *ARoute
- func (r *ARoute) Port(p string) *ARoute
- func (r *ARoute) Protocal(p ...string) *ARoute
- func (r *ARoute) Queries(q ...string) *ARoute
- func (r *ARoute) Schemes(schemes ...string) *ARoute
- type Collision2
- type FromType
- type GoGoWidgetFunc
- type GoGoWidgetMatchFunc
- type GoGoWidgetSet
- type GoGoWidgetSetMatch
- type Handle
- type HandleFunc
- type LogInfo
- type LogIt
- type Match
- type MatchFunc
- type MatchItRankType
- type MidBuffer
- func (b *MidBuffer) DumpBuffer()
- func (b *MidBuffer) EmptyBody()
- func (b *MidBuffer) FinalFlush()
- func (b *MidBuffer) Flush()
- func (b *MidBuffer) GetBody() (s []byte)
- func (b *MidBuffer) GetHeader() (h http.Header)
- func (b *MidBuffer) GetModtime() time.Time
- func (b *MidBuffer) Header() http.Header
- func (b *MidBuffer) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (b *MidBuffer) ReplaceBody(buf []byte)
- func (rw *MidBuffer) SaveCurentBody(body string)
- func (b *MidBuffer) Searilize()
- func (b *MidBuffer) Write(buf []byte) (int, error)
- func (b *MidBuffer) WriteHeader(StatusCode int)
- func (b *MidBuffer) WriteRow(row map[string]interface{}) error
- func (b *MidBuffer) WriteTable(d []map[string]interface{}) error
- type MuxRouter
- func (r *MuxRouter) AttachWidget(w Where, fx GoGoWidgetFunc)
- func (r *MuxRouter) CmpUrlToCleanRoute(trr *MuxRouterProcessing, UsePat string, CleanUrl string) (rv bool)
- func (r *MuxRouter) Comment(c string) *ARoute
- func (r *MuxRouter) CompileRoutes()
- func (r *MuxRouter) DebugMatch(tf bool)
- func (r *MuxRouter) DumpRouteData(msg string)
- func (r *MuxRouter) FixBadUrl(trr *MuxRouterProcessing, Url string) (rv string, fixed bool)
- func (r *MuxRouter) GetArgs4(trr *MuxRouterProcessing, Url string, _ string, names []string, _ int, ...)
- func (r *MuxRouter) HandleFunc(path string, f HandleFunc) *ARoute
- func (r *MuxRouter) Headers(pairs ...string) *ARoute
- func (r *MuxRouter) Host(h string) *ARoute
- func (r *MuxRouter) HostPort(h string) *ARoute
- func (r *MuxRouter) HostPort_AllRoutes(hp ...string) *MuxRouter
- func (r *MuxRouter) Id(n int) *ARoute
- func (r *MuxRouter) ListRoutes() []*ARoute
- func (r *MuxRouter) LookupUrlViaHash2(trr *MuxRouterProcessing, w http.ResponseWriter, req *http.Request, m *int) (found bool, ln int, rv Collision2)
- func (r *MuxRouter) MatchAndServeHTTP(www http.ResponseWriter, req *http.Request) (Found bool, err error)
- func (r *MuxRouter) Methods(methods ...string) *ARoute
- func (r *MuxRouter) Name(n string) *ARoute
- func (r *MuxRouter) NewRoute() *ARoute
- func (r *MuxRouter) Path(tpl string) *ARoute
- func (r *MuxRouter) PathPrefix(p string) *ARoute
- func (r *MuxRouter) Port(p string) *ARoute
- func (r *MuxRouter) Protocal(p ...string) *ARoute
- func (r *MuxRouter) Queries(q ...string) *ARoute
- func (r *MuxRouter) Schemes(schemes ...string) *ARoute
- func (r *MuxRouter) ServeFiles(path string, root http.FileSystem)
- func (r *MuxRouter) ServeHTTP(www http.ResponseWriter, req *http.Request)
- func (r *MuxRouter) SplitOnSlash3(trr *MuxRouterProcessing, m int, Url string, isUrl bool)
- func (r *MuxRouter) UrlToCleanRoute(trr *MuxRouterProcessing, UsePat string) (rv string)
- func (r *MuxRouter) WidgetMatch(MatchIt []Match, www http.ResponseWriter, req *http.Request, m *int, ...) bool
- type MuxRouterProcessing
- type Param
- type ParamType
- type Params
- func (ps *Params) ByName(name string) (rv string)
- func (ps *Params) ByNameDflt(name string, dflt string) (rv string)
- func (ps *Params) ByPostion(pos int) (name string, val string, outRange bool)
- func (ps *Params) CreateSearch()
- func (ps *Params) DumpParam() (rv string)
- func (ps *Params) DumpParamDB() (rv string)
- func (ps *Params) DumpParamNVF() (rv []common.NameValueFrom)
- func (ps *Params) DumpParamTable() (rv string)
- func (ps *Params) DumpParamUsed(ign ...string) (rv string)
- func (ps *Params) GetAllParam(skip ...string) (rv []common.NameValueFrom)
- func (ps *Params) GetByName(name string) (rv string, found bool)
- func (ps *Params) GetByNameAndType(name string, ft FromType) (rv string, found bool)
- func (ps *Params) HasName(name string) (rv bool)
- func (ps *Params) IsMatchUnused(NormalUnused []UnusedParam, aName string) bool
- func (ps *Params) MakeStringMap(mdata map[string]string)
- func (ps *Params) PositionOf(name string) (rv int)
- func (ps *Params) ReportUnexpectedUnused(NormalUnused []UnusedParam)
- func (ps *Params) SetValue(name string, val string)
- type Re
- type ReList
- type RouteData
- type SearilizeType
- type StateType
- type UnusedParam
- type UrlAPat
- type UrlPat
- type Where
Constants ¶
const ( ReMatch MatchItRankType = 1 << iota // Not used anymore HeaderMatch = 1 << iota // Has a match on the HTTP Headers QueryMatch = 1 << iota // Has a match on the query - stuff after question mark TLSMatch = 1 << iota // Matches "https" v.s. "http" PortMatch = 1 << iota // Has a match on the Port HostMatch = 1 << iota // Has a match on the Host PortHostMatch = 1 << iota // Matches both Host and Port ProtocalMatch = 1 << iota // Has a match on prococal, http/1.0, http/1.1, http/2.0 User0Match = 1 << iota // Reserved for User Functions User1Match = 1 << iota // Reserved for User Functions User2Match = 1 << iota // Reserved for User Functions User3Match = 1 << iota // Reserved for User Functions User4Match = 1 << iota // Reserved for User Functions )
const ( HashNewM Where = iota Before = iota After = iota )
const ( IsWord colType = 1 << iota MultiUrl = 1 << iota SingleUrl = 1 << iota Dummy = 1 << iota )
const ApacheFormatPattern = "%s %v %s %s %s %v %d %v\n"
const MaxParams = 200
const MaxSlashInUrl = 20
-------------------------------------------------------------------------------------------------
Variables ¶
var ApacheLogFile *os.File
-------------------------------------------------------------------------------------------------
Functions ¶
func AddValueToParams ¶
-------------------------------------------------------------------------------------------------
func ApacheLogingBefore ¶
func DumpMatchItRan ¶
func DumpMatchItRan(x MatchItRankType) (rv string)
func FixPath ¶
Parse a path and make corrections to it. Remove double slash, "//". Remove all "./". Convert "name/../" to empty string. Return the number of used elements in the 'rv' slice, and place one token from the path in each of the elements of the 'rv' slice. If the path is a hard path (Starts from /) then the 0th element of the rv slice will be "/". The rv slice is assumed to be long enough to hold all the elements of the path. max is the maximum number of elements that will be used in 'rv'.
func FromTypeToString ¶
func GetCurTime ¶
func GetCurTime() (s string)
func InitMuxRouterProcessing ¶
func InitMuxRouterProcessing(r *MuxRouter, trr *MuxRouterProcessing)
func InitParams ¶
func InitParams(p *Params)
func IsMapStringBoolEmpty ¶
func LastIndexOfChar ¶
Find the last index of the character 'ch' in 's'. Example
n := LastIndexOfChar( "[123:456]:80", ':' )
will return 9 -1 is returned if not found.
func LineFile ¶
Return the line number and file name. A single depth paramter 'd' can be supplied. 1 is the routien that called LineFile, 2 is the caller of the routine that called LineFile etc.
func MethodParam ¶
-------------------------------------------------------------------------------------------------
func MethodParamReg ¶
func MethodToCode ¶
func OrderedBy ¶
func OrderedBy(less ...lessFunc) *multiSorter
OrderedBy returns a Sorter that sorts using the less functions, in order. Call its Sort method to sort the data.
func OrderedByPat ¶
func OrderedByPat(less ...lessFuncPat) *multiSorterPat
OrderedBy returns a Sorter that sorts using the less functions, in order. Call its Sort method to sort the data.
func ParseBodyAsParams ¶
------------------------------------------------------------------------------------------------- func ParseBodyAsParams(w *MyResponseWriter, req *http.Request, ps *Params) int {
func ParseBodyAsParamsReg ¶
-------------------------------------------------------------------------------------------------
func ParseCookiesAsParams ¶
-------------------------------------------------------------------------------------------------
func ParseCookiesAsParamsReg ¶
-------------------------------------------------------------------------------------------------
func ParseQueryParams ¶
-------------------------------------------------------------------------------------------------
func ParseQueryParamsReg ¶
func PeekAtBody ¶
func PrefixWith ¶
-------------------------------------------------------------------------------------------------
func RenameReservedItems ¶
func SVar ¶
func SVar(v interface{}) string
--------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------
func SVarI ¶
func SVarI(v interface{}) string
--------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------
func ServeHTTP ¶
func ServeHTTP(fx func(w http.ResponseWriter, r *http.Request)) (rv func(res http.ResponseWriter, req *http.Request, ps Params))
func SetCurTime ¶
func SetCurTime(s string)
func SetupUnsedParam ¶
func SetupUnsedParam(NormalUnused []UnusedParam)
Types ¶
type ARoute ¶
type ARoute struct { DId int // Used for testing DName string // Used to identify a route by name DPath string // Set by Handler("/path",Fx), Path(), PathPrefix() DPathPrefix string // -- Concatenated on front of path -- DHandlerFunc HandleFunc // DHeaders []string // Set by Headers() DHost string // Set by Host() DPort string // Set by Port() DHostPort string // Set by HostPort() DMethods []string // Set by Methods() List of methods, GET, POST etc. DSchemes []string // Set by Schemes() https, http etc. DQueries []string // Set by Queries() DProtocal map[string]bool // Set by Protocal() https == TLS on, http == no TLS, both is no-check(default) DComment string // Set by Comment() DUser map[string]interface{} // Can be set by user to data needed in matches. HeaderMatchMap map[string]string // Map constructed form pairs of DHeaders QueryMatchMap map[string]string // Map constructed form pairs of DQueries FileName string // Line no && File name where this was defined LineNo int // // contains filtered or unexported fields }
func (*ARoute) AppendFileName ¶
---------------------------------------------------------------------------- Manpiulate LineNo/FileName in ARoute data. ----------------------------------------------------------------------------
func (*ARoute) HandleFunc ¶
func (r *ARoute) HandleFunc(path string, f HandleFunc) *ARoute
HandleFunc registers a new route with a matcher for the URL path.
func (*ARoute) Id ¶
Id sets the name for this route. This is not used for matching the route. This is used in testing.
func (*ARoute) PathPrefix ¶
PathPrefix registers a new route with a matcher for the URL path prefix.
func (*ARoute) Port ¶
Port sets the port or this route. This is a string like "80" or "8000" xyzzy - ports are numbers ? validate!
type Collision2 ¶
type Collision2 struct { Url string // /path/:v1/:v2/whatever Comment string // Optionally set comment on what is getting called. NSL int // number of / in the URL/Route CleanUrl string // /path/:/:/whatever Hdlr int // User specified int, mostly for testing Fx HandleFunc // Function to call to handle this request TPat string // T::T ArgNames []string // ArgPattern string // T::T dup?? not used LineNo int // Location this was created FileName string // Location this was created HasRe []ReList // Set of RE that is required to match this Collision2 MatchIt []Match // If additional matching criteria are used Multi map[string]Collision2 // if (cType&MultiUrl)!=0, then use string to disambiguate collisions // contains filtered or unexported fields }
type GoGoWidgetFunc ¶
type GoGoWidgetFunc func(http.ResponseWriter, *http.Request, *Params, *GoGoData, int) int type GoGoWidgetFunc func(*MyResponseWriter, *http.Request, *Params) int
type GoGoWidgetMatchFunc ¶
type GoGoWidgetSet ¶
type GoGoWidgetSet struct {
// contains filtered or unexported fields
}
type GoGoWidgetSetMatch ¶
type GoGoWidgetSetMatch struct {
// contains filtered or unexported fields
}
type Handle ¶
type Handle func(w http.ResponseWriter, req *http.Request)
Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of parameters. Parameters can be from the URL or from other sources. ///// type Handle func(w http.ResponseWriter, req *http.Request, ps Params) // xyzzyGoFtl - marker
type HandleFunc ¶
type HandleFunc Handle
I will use this type (synonomous with Handle) as HandleFunc is a unique string and Handle is just a word. type HandleFunc func(w http.ResponseWriter, req *http.Request, ps Params)
type LogInfo ¶
func (*LogInfo) TraceEnabled ¶
type MatchItRankType ¶
type MatchItRankType uint32
type MidBuffer ¶
type MidBuffer struct { StatusCode int // StatusCode like 200, 404 etc. Headers http.Header // All the headers that will be writen when done Length int64 // Length of the response Error error // Most recent error, if StatusCode == 200, then ignore Prefix string // Tack onto response when you flush. Postfix string // IndentFlag bool // If JSON/JsonX/XML searilize will searilize it with indentation Row map[string]interface{} // Single Row Response -- or table header info Table []map[string]interface{} // Table of Row Response State StateType // Byte, Row, Table SearilizeFormat SearilizeType // Byte, Row, Table StartTime time.Time // Start time for deltaT and proxy timeout -- deltaT := time.Since(mb.StartTime).String() Modtime time.Time // file modification time NRewrite int // # of rewrites that have occured - may be a limit on this (prevents loops) RerunRequest bool // AddInfo map[string]string // Way to pass info from middleware to middleware (Session) MapLock sync.Mutex // Lock for accesing maps in this. Ps Params // xyzzyParams - PJS - change request interface to pass/parse 'params' as modifed req Next http.Handler // Required field for all chaining of middleware. Hdlr interface{} // Handler to the "TOP" or nil ResolvedFn string // Single file name - resolved to local from fileserver DependentFNs []string // Set of files that if any have chagned (mod-datetime) then should not cache and let lower levels re-generate IsProxyFile bool // File was fetched by a proxy to another server - it is NOT(local) SaveDataInCache bool // If true then save the data in the cache (gzip -> new data) DirTemplateFileName string // TemplateLineNo int // IgnoreDirs []string // OriginalURL string // G_Trx interface{} // Extend map[string]interface{} // RequestTrxId string // // Id for the entire request // IsHijacked bool // ParsedHTML interface{} // New data ParsedCSS interface{} // New data PackedData interface{} // New data Dependencies interface{} // New data Session *RedisSessionData.RedisSessionDataType // // contains filtered or unexported fields }
------------------------------------------------------------------------------------------------------------ Implement a compatible http.ResponseWriter that saves all the data until the end. Good side: you don't need to finish your headers before your data. Good side: you can post-process the data/status. Good side: length header can be manipulated after the data is generated. Bad side: This won't work with a streaming data interface at all. Bad side: Also it's all buffered in memory. -- Not that big a deal - and common to all proxy usages anyhow.
func NewMidBuffer ¶
func NewMidBuffer(w http.ResponseWriter, hdlr interface{}) (rv *MidBuffer)
Return a new buffered http.ResponseWriter
func (*MidBuffer) DumpBuffer ¶
func (b *MidBuffer) DumpBuffer()
---------------------------------------------------------------------------------------------------------------------------------------
func (*MidBuffer) FinalFlush ¶
func (b *MidBuffer) FinalFlush()
---------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------- FinalFlush will actually do the flush and is used at the top level. It also addss any prefix/postfix text to the response. Prefix for JSON might be "while(1);"
func (*MidBuffer) GetModtime ¶
func (*MidBuffer) ReplaceBody ¶
func (*MidBuffer) SaveCurentBody ¶
func (*MidBuffer) WriteHeader ¶
Implement http.ResponseWriter WriteHeader to just buffer the Status
func (*MidBuffer) WriteTable ¶
type MuxRouter ¶
type MuxRouter struct { NotFoundHandler http.Handler // Configurable Handler to be used when no route matches. UseRedirect bool // PJS AllHostPortFlag bool AllHostPort map[string]int // ------------------------------------------------------------------------------------------------------ // The hash of paths/URLs // HashItems []HashItem Hash2Test []int MaxSlash int // Maximum number of slashes found in any route -- generated during route compile -- // ------------------------------------------------------------------------------------------------------ // User settable handler called when no match is found. Type: http.HandlerFunc. // If not set then http.NotFound will be called. NotFound http.HandlerFunc // ------------------------------------------------------------------------------------------------------ // Function to handle panics recovered from http handlers. // It should be used to generate a error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecovered panics. PanicHandler func(http.ResponseWriter, *http.Request, interface{}) // ------------------------------------------------------------------------------------------------------ HasBeenCompiled bool // Flag, set to true when the routes are compiled. LookupResults []Collision2 DebugMatchOn bool // contains filtered or unexported fields }
func (*MuxRouter) AttachWidget ¶
func (r *MuxRouter) AttachWidget(w Where, fx GoGoWidgetFunc)
Attach middlewhare widget to the handler.
func (*MuxRouter) CmpUrlToCleanRoute ¶
func (r *MuxRouter) CmpUrlToCleanRoute(trr *MuxRouterProcessing, UsePat string, CleanUrl string) (rv bool)
compate r.CurUrl to a Pattern
func (*MuxRouter) CompileRoutes ¶
func (r *MuxRouter) CompileRoutes()
func (*MuxRouter) DebugMatch ¶
func (*MuxRouter) DumpRouteData ¶
func (*MuxRouter) FixBadUrl ¶
func (r *MuxRouter) FixBadUrl(trr *MuxRouterProcessing, Url string) (rv string, fixed bool)
With a known bad URL, that has //, /./, or /../ in it, fix the URL.
func (*MuxRouter) GetArgs4 ¶
func (r *MuxRouter) GetArgs4(trr *MuxRouterProcessing, Url string, _ string, names []string, _ int, ps *Params)
------------------------------------------------------------------------------------------------- Extract arguments from the URL.
func (*MuxRouter) HandleFunc ¶
func (r *MuxRouter) HandleFunc(path string, f HandleFunc) *ARoute
HandleFunc registers a new route with a matcher for the URL path.
func (*MuxRouter) HostPort ¶
Host:Port registers a new route with a matcher for the URL host and port.
func (*MuxRouter) HostPort_AllRoutes ¶
Set/Append to list of valid host/ports for all routes by this router
func (*MuxRouter) Id ¶
Id sets the name for this route. This is not used for matching the route. This is used in testing.
func (*MuxRouter) ListRoutes ¶
Just return the data for the routes that are built
func (*MuxRouter) LookupUrlViaHash2 ¶
func (r *MuxRouter) LookupUrlViaHash2(trr *MuxRouterProcessing, w http.ResponseWriter, req *http.Request, m *int) (found bool, ln int, rv Collision2)
func (*MuxRouter) MatchAndServeHTTP ¶
func (*MuxRouter) PathPrefix ¶
PathPrefix registers a new route with a matcher for the URL path prefix.
func (*MuxRouter) Port ¶
Port sets the port or this route. This is a string like "80" or "8000" xyzzy
func (*MuxRouter) Queries ¶
Queries registers a new route with a matcher for URL query values. xyzzy
func (*MuxRouter) ServeFiles ¶
func (r *MuxRouter) ServeFiles(path string, root http.FileSystem)
ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:
router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
func (*MuxRouter) ServeHTTP ¶
func (r *MuxRouter) ServeHTTP(www http.ResponseWriter, req *http.Request)
-------------------------------------------------------------------------------------------------
func (*MuxRouter) SplitOnSlash3 ¶
func (r *MuxRouter) SplitOnSlash3(trr *MuxRouterProcessing, m int, Url string, isUrl bool)
xyzzy-hash
func (*MuxRouter) UrlToCleanRoute ¶
func (r *MuxRouter) UrlToCleanRoute(trr *MuxRouterProcessing, UsePat string) (rv string)
Input: Pattern like T::T and the current URL with Slash locaiton information. So... /abc/:def/ghi is the Route, /abc/x/ghi is the ULR, Slash is [ 0, 4, 6, 10 ] The output is /abc/:/ghi - Sutiable for lookup in a map of cleanRoute
type MuxRouterProcessing ¶
type MuxRouterProcessing struct { // Info used during processing of a URL --- This is bad --- This can not go into this struct!!!!!!!!!!!!! // ------------------------------------------------------------------------------------------------------ CurUrl string // The current URL being processed. Hash [MaxSlashInUrl]int // The set of hash keys in the current operation. Slash [MaxSlashInUrl + 1]int // Array of locaitons for the '/' in the url. For /abc/def, it would be [ 0, 4, 8 ] NSl int // Number of slashes in the URL for /abc/def it would be 2 UsePat string // The used T::T pattern for matching - at URL time. // contains filtered or unexported fields }
MuxRouter registers routes to be matched and dispatches a handler.
// xyzzy - change this comment to be accurate It implements the http.Handler interface, so it can be registered to serve requests:
var router = mux.NewRouter() func main() { http.Handle("/", router) }
Or, for Google App Engine, register it in a init() function:
func init() { http.Handle("/", router) }
This will send all incoming requests to the router. MaxSlash int // Maximum number of slashes found in any route - taken from compiling the routes
type Param ¶
type Param struct { Name string Value string From FromType Type ParamType UsedAt int UsedFile string }
Param is a single URL parameter, consisting of a key and a value.
type Params ¶
type Params struct { NParam int // Data []Param // has to be assided to array // contains filtered or unexported fields }
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
func (*Params) ByName ¶
ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.
func (*Params) CreateSearch ¶
func (ps *Params) CreateSearch()
func (*Params) DumpParamDB ¶
func (*Params) DumpParamNVF ¶
func (ps *Params) DumpParamNVF() (rv []common.NameValueFrom)
func (*Params) DumpParamTable ¶
func (*Params) DumpParamUsed ¶
func (*Params) GetAllParam ¶
func (ps *Params) GetAllParam(skip ...string) (rv []common.NameValueFrom)
func (*Params) GetByNameAndType ¶
func (*Params) IsMatchUnused ¶
func (ps *Params) IsMatchUnused(NormalUnused []UnusedParam, aName string) bool
func (*Params) MakeStringMap ¶
func (*Params) PositionOf ¶
func (*Params) ReportUnexpectedUnused ¶
func (ps *Params) ReportUnexpectedUnused(NormalUnused []UnusedParam)
type ReList ¶
type ReList struct { Hdlr int // User specified int, mostly for testing Fx HandleFunc // Function to call to handle this request ArgNames []string // ReSet []Re MatchIt []Match // contains filtered or unexported fields }
type RouteData ¶
type RouteData struct { Method string // GET, PUT ... Route string // Route Pattern /abc/:def/ghi Hdlr int // User supplied integer returned on finding route NFxNo int // Index into []ARoute on what function to use Ns int // MatchIt []Match // Array of potential matches with regular expressions MatchItRank MatchItRankType // }
type SearilizeType ¶
type SearilizeType int
const ( SearilizeJSON SearilizeType = iota SearilizeXML SearilizeHTML SearilizeCSV SearilizeTemplate )