Documentation
¶
Overview ¶
NanoMux is a package of HTTP request routers for the Go language.
The package has three types that can be used as routers. The first one is the Resource, which represents the path segment resource. The second one is the Host. it represents the host segment of the URL but also takes on the role of the root resource when HTTP method handlers are set. The third one is the Router which supports registering multiple hosts and resources. It passes the request to the matching host and, when there is no matching host, to the root resource. In NanoMux terms, hosts and resources are called responders.
Responders are organized into a tree. The request's URL segments are matched against the host and corresponding resources' templates in the tree. The request passes through each matching responder in its URL until it reaches the last segment's responder. To pass the request to the next segment's responder, the request passers of the Router, Host, and Resource are called. When the request reaches the last responder, that responder's request handler is called. The request handler is responsible for calling the responder's HTTP method handler. The request passer, request handler, and HTTP method handlers can all be wrapped with middleware.
The NanoMux types provide many methods, but most of them are for convenience. Sections below discuss the main features of the package.
Templates ¶
Based on the segments they comprise, there are three types of templates: static, pattern, and wildcard.
Static templates have no regex or wildcard segments.
// Static temlates "/news/" "forecast" "https:///blog" "http://example.com"
Pattern templates have one or more regex segments and/or one wildcard segment and static segments. A regex segment must be in curly braces and consists of a value name and a regex pattern separated by a colon: "{valueName:regexPattern}". The wildcard segment only has a value name: "{valueName}". There can be only one wildcard segment in a template.
// Pattern templates
"http:///{category}-news/"
`name:{name:[A-Za-z]{2,}}, id:{id:(AA|CN)\d{5}}`
"/{color:red|green|blue}_{carModel}"
"https://{sub}.example.com/"
Wildcard templates have only one wildcard segment and no static or regex segments.
// Wildcard templates
"/{city}"
"{article}"
// Hosts cannot have a wildcard template.
The host segment templates must always follow the scheme with the colon ":" and the two slashes "//" of the authority component. The path segment templates may be preceded by a slash "/" or a scheme, a colon ":", and three slashes "///" (two authority component slashes and the third separator slash). Like in "https:///blog". The preceding slash is just a separator. It doesn't denote the root resource, except when it is used alone. The template "/" or "https:///" denotes the root resource. Both the host and path segment templates can have a trailing slash. When its template starts with "https" unless configured to redirect, the host or resource will not handle a request when used under HTTP and respond with a "404 Not Found" status code. When its template has a trailing slash unless configured to be lenient or strict, the resource will redirect the request that was made to a URL without a trailing slash to the one with a trailing slash and vice versa. The trailing slash has no effect on the host. But if the host is a subtree handler and should respond to the request, its configurations related to the trailing slash will be used on the last path segment.
As a side note, every parent resource should have a trailing slash in its template. For example, in a resource tree "/parent/child/grandchild", two non-leaf resources should be referenced with templates "parent/" and "child/". NanoMux doesn't force this, but it's good practice to follow. It helps the clients avoid forming a broken URL when adding a relative URL to the base URL. By default, if the resource has a trailing slash, NanoMux redirects the requests made to the URL without a trailing slash to the URL with a trailing slash. So the clients will have the correct URL.
Templates can have a name. The name segment comes at the beginning of the host or path segment templates, but after the slashes. The name segment begins with a "$" sign and is separated from the template's contents by a colon ":". The template's name comes between the "$" sign and the colon ":". The name given in the template can be used to retrieve the host or resource from its parent (the router is considered the host's parent).
// Named templates
"$blog:blog"
"/$category:{category}"
`http:///$id:{id:\d{3}}`
"https://$host:{sub2}.{sub1}.example.com"
For convenience, a regex segment's or wildcard segment's value name is used as the name of the template when there is no template name and no other regex segments. For example, templates "{color:red|green|blue}", `day {day:(?:3[01]|[12]\d|0?[1-9])}`, "{model}" have names color, day, and model, respectively.
If the template's static part needs a "$" sign at the beginning or curly braces anywhere, they can be escaped with a backslash `\`. Like in the template `\$tatic\{template\}`. For some reason, if the template name or value name needs a colon ":", it can also be escapbed with a backslash: `$smileys\:):{smiley\:)}`. When retrieving the host, resource, or value of the regex or wildcard segment, names are used unescaped without a backslash `\`.
Constructors of the Host and Resource types and some methods take URL templates or path templates.
// URL templates
"https://example.com"
"http://example.com/blogs/"
"https://www.example.com/$user:{userName}"
`https://$news:news.example.com/$newsType:{type}/{id:\d{6}}`
// Path templates
`/$proCat:{productCategory}/{id:\d{6}}`
"https:///{singer}/albums/{albumName}/"
"latest-news"
In the URL and path templates, the scheme and trailing slash belong to the last segment. In the URL template, after the host segment, if the path component contains only a slash "/", it's considered a trailing slash of the host template. The host template's trailing slash is used only for the last path segment when the host is a subtree handler and should respond to the request. It has no effect on the host itself.
In templates, disallowed characters must be used without a percent-encoding, except for a slash "/". Because the slash "/" is a separator when needed in a template, it must be replaced with %2f or %2F.
Hosts and resources may have child resources with all three types of templates. In that case, the request's path segments are first matched against child resources with a static template. If no resource with a static template matches, then child resources with a pattern template are matched in the order of their registration. Lastly, if there is no child resource with a pattern template that matches the request's path segment, a child resource with a wildcard template accepts the request. Hosts and resources can have only one direct child resource with a wildcard template.
Usage ¶
The Host and Resource types implement the http.Handler interface. They can be constructed, have HTTP method handlers set with the SetHandlerFor method, and can be registered with the RegisterResource or RegisterResourceUnder methods to form a resource tree.
There is one restriction: the root resource cannot be registered under a host. It can be used without a host or be registered with the router. When the Host type is used, the root resource is implied.
// GetBlogs is the GET HTTP method's handler of the resource "blogs".
func GetBlogs(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// GetBlog is the GET HTTP method's handler of the resource "blog".
func GetBlog(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// HostPathValues does not return query component values.
// Hence the name :)
var hpVs = args.HostPathValues()
var blogTitle = hpVs.Get("blog")
// ...
}
// ShareBlog is the SHARE custom HTTP method's handler of the resource
// "blog".
func ShareBlog(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var hpVs = args.HostPathValues()
var blogTitle = hpVs.Get("blog")
// ...
}
// ...
// A resource is dormant until it gets an HTTP method handler.
// The "blogs" resource will have a child resource. It's good practice
// for every parent resource to have a trailing slash "/".
// /blogs/
var blogs = nanomux.NewDormantResource("blogs/")
blogs.SetHandlerFor("GET", GetBlogs)
var blog = nanomux.NewDormantResource("{blog}")
blog.SetHandlerFor("GET", GetBlog)
// SHARE is a custom HTTP method.
blog.SetHandlerFor("SHARE", ShareBlog)
// /blogs/{blog}
blogs.RegisterResource(blog)
// ...
var err = http.ListenAndServe(":8000", blogs)
if err != nil {
// ...
}
Handlers must return true if they respond to the request. Sometimes middlewares and the responder itself need to know whether the request was handled or not. For example, when the middleware responds to the request instead of calling the request passer, the responder may assume that none of its child resources responded to the request in its subtree, so it responds with "404 Not Found" to the request that was already responded to. To prevent this, the middleware's handler must return true if it responds to the request, or it must return the value returned from the argument handler.
Sometimes resources have to handle HTTP methods they don't support. NanoMux provides a default not allowed HTTP method handler that responds with a "405 Method Not Allowed" status code, listing all HTTP methods the resource supports in the "Allow" header. But when the host or resource needs a custom implementation, its SetHandlerFor method can be used to replace the default handler. To denote the not allowed HTTP method handler, the exclamation mark "!" must be used instead of an HTTP method.
func HandleNotAllowedMethod(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// ...
blogs.SetHandlerFor("!", HandleNotAllowedMethod)
In addition to the not allowed HTTP method handler, if the host or resource has at least one HTTP method handler, NanoMux also provides a default OPTIONS HTTP method handler.
The host and resource allow setting a handler for a child resource in their subtree. If the subtree resource doesn't exist, it will be created.
func PostBlog(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var hpVs = args.HostPathValues()
var blogTitle = hpVs.Get("blog")
// ...
}
// ...
// After the following method call, the "blog" resource will have the
// POST HTTP method's handler.
blogs.SetPathHandlerFor("POST", "{blog}", PostBlog)
It's possible to retrieve a subtree resource with the method Resource. If the subtree resource doesn't exist, the method Resource creates it. If an existing resource must be retrieved, the method RegisteredResource can be used.
func Get5or10DaysForecast(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var hpVs = args.HostPathValues()
var numberOfDays = hpVs.Get("numberOfDays")
// ...
}
// ...
var root = nanomux.NewDormantResource("/")
var nDaysForecast = root.Resource("forecast/{numberOfDays:5|10}_days")
nDaysForecast.SetHandlerFor("GET", Get5or10DaysForecast)
// There is no need to register the resource "nDaysForecast".
// It's already in the root's subtree.
// ...
var err = http.ListenAndServe(":8000", root)
if err != nil {
// ...
}
Sharing Data Between Handlers ¶
If there is a need for shared data, it can be set with the SetSharedData method of the Host and Resource. The shared data can then be retrieved in the handlers calling the ResponderSharedData method of the passed *Args argument.
var blogsMap = &sync.Map{}
// ...
func GetBlogs(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var blogsMap = args.ResponderSharedData().(*sync.Map)
// ...
}
func PostBlog(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var hpVs = args.HostPathValues()
var blogTitle = hpVs.Get("blog")
var blogsMap = args.ResponderSharedData().(*sync.Map)
// ...
}
// ...
blogs.SetHandlerFor("GET", GetBlogs)
blogs.SetSharedData(blogsMap)
blog.SetHandlerFor("POST", PostBlog)
blog.SetSharedData(blogsMap)
Hosts and resources can have their own shared data. Handlers retrieve the shared data of their responder.
Sharing Data via Args ¶
The responder's SetSharedData is useful for sharing data between its handlers. But, when the data needs to be shared between responders in the resource tree, the *Args argument can be used. The Set method of the *Args argument takes a key and a value of any type and sets the value for the key. The rules for defining a key are the same as for "context.Context". Any responder can set as many values as needed when it's passing or handling a request. The *Args argument carries the values between middlewares and handlers as the request passes through the matching responders in the resource tree.
type (
_Key struct{}
Value struct {
// ...
}
)
var Key any = _Key{}
// ...
func Mw(handler nanomux.Handler) nanomux.Handler {
return func(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var value = &Value{
// ...
}
args.Set(Key, value)
return handler(w, r, args)
}
}
func GetSectorStats(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var sector = args.HostPathValues().Get("sector")
var value = args.Get(Key).(*Value)
// ...
}
// ...
var root = nanomux.NewDormantResource("/")
root.WrapRequestPasser(Mw)
root.SetPathHandlerFor("GET", "stats/{sector}", GetSectorStats)
var err = http.ListenAndServe(":8000", root)
if err != nil {
// ...
}
Implementation ¶
Hosts and resources can be implemented as a type with methods. Each method that has a name beginning with "Handle" and has the signature of a nanomux.Handler is used as an HTTP method handler. The remaining part of the method's name is considered an HTTP method.
// The implementation of the resource "posts".
type Posts struct {
// ...
}
// Constructor of the "posts" resource.
func NewPosts() *nanomux.Resource {
var postsImpl = &Posts{
// ...
}
return nanomux.NewResource("posts", postsImpl)
}
// GET HTTP method's handler.
func (posts *Posts) HandleGet(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// SHARE custom HTTP method's handler.
func (posts *Posts) HandleShare(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// Not allowed HTTP method handler.
func (posts *Posts) HandleNotAllowedMethod(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
It is possible to set the implementation later with the SetImplementation method of the Host and Resource. The implementation may also be set for a child resource in the subtree with the method SetImplementationAt.
var postsImpl = &Posts{
// ...
}
var host = nanomux.NewDormantHost("http://example.com")
host.SetImplementationAt("/posts", postsImpl)
Subtree Handler ¶
Hosts and resources configured to be a subtree handler respond to the request when there is no matching resource in their subtree.
In the resource tree,
// / ─ resource-1 ┬ resource-11 ─ resoruce-111 ─ resource-1111 // │ // └ resource-12 ┬ resource-121 // └ resource-122
if resource-12 is a subtree handler, it handles the request to a path "/resource-1/resource-12/non-existent-resource". Subtree handlers can get the remaining part of the path with the RemainingPath method of the *Args argument. The remaining path starts with a slash "/" if the subtree handler has no trailing slash in its template, otherwise it starts without a trailing slash.
A subtree handler can also be used as a file server.
func NewFileServer(resourcePath, directory string) *nanomux.Resource {
var fs = http.FileServer(http.Dir(directory))
var handleGet = func(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
var rawRemainingPath = args.RemainingPath()
r.URL.RawPath = rawRemainingPath
var remainingPath, err = url.PathUnescape(rawRemainingPath)
if err != nil {
http.Error(
w,
http.StatusText(http.StatusBadRequest),
http.StatusBadRequest,
)
return true
}
r.URL.Path = remainingPath
fs.ServeHTTP(w, r)
return true
}
var r = nanomux.NewDormantResourceUsingConfig(
resourcePath,
nanomux.Config{
SubtreeHandler: true,
},
)
r.SetHandlerFor("GET", handleGet)
return r
}
// ...
// resource path: "static/", directory: "./static/"
var fs = NewFileServer("static/", "./static/")
var err = http.ListenAndServe(":8000", fs)
if err != nil {
// ...
}
Middleware ¶
Let's say we have the following resource tree:
// http://example.com ┬ resource-1 ┬ resource-11 // │ └ resoruce-12 ─ resource-121 // │ // └ resource-2 ─ resource-21
When the request is made to a URL "http://example.com/resource-1/resource-12", the host's request passer is called. It passes the request to the resource-1. Then the resource-1's request passer is called and it passes the request to the resource-12. The resource-12 is the last resource in the URL, so its request handler is called. The request handler is responsible for calling the resource's HTTP method handler. If there is no handler for the request's method, it calls the not allowed HTTP method handler. All of these handlers and the request passer can be wrapped in middleware.
func GetGroups(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
func CredentialsAreValid(r *http.Request) bool {
// ...
}
// Middleware
func CheckCredentials(nextHandler nanomux.Handler) nanomux.Handler {
return func(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
if CredentialsAreValid(r) {
return nextHandler(w, r, args)
}
// http.Error(
// w,
// http.StatusText(http.StatusUnauthorized),
// http.StatusUnauthorized,
// )
// When the middleware's handler responds to a request instead of
// calling the next handler, it must return true.
// return true
return false
}
}
// ...
var host = nanomux.NewDormantHost("http://example.com")
host.SetPathHandlerFor("GET", "/admin/groups", GetGroups)
host.WrapRequestPasserAt("/admin/", CheckCredentials)
// ...
var err = http.ListenAndServe(":8000", host)
if err != nil {
// ...
}
In the above snippet, the WrapRequestPasserAt method wraps the request passer of the "admin" resource with the CheckCredentials middleware. The CheckCredentials calls the "admin" resource's request passer if the credentials are valid; if not, no further segments will be matched, the request will be dropped, and the client will be responded with a "404 Not Found" status code.
In the above case, "admin" is a dormant resource. But as its name states, the request passer's purpose is to pass the request to the next resource. It's called even when the resource is dormant.
Unlike the request passer, the request handler is called only when the host or resource is the one that must respond to the request. The request handler can be wrapped when the middleware must be called before any HTTP method handler.
The WrapRequestPasser, WrapRequestHandler, and WrapHandlerOf methods of the Host and Resource types wrap their request passer, request handler, and the HTTP method handlers, respectively. The WrapRequestPasserAt, WrapRequestHandlerAt, and WrapPathHandlerOf methods wrap the request passer and the respective handlers of the child resource at the path. The WrapSubtreeRequestPassers, WrapSubtreeRequestHandlers, and WrapSubtreeHandlersOf methods wrap the request passer and the respective handlers of all the resources in the host's or resource's subtree.
When calling the WrapHandlerOf, WrapPathHandlerOf, and WrapSubtreeHandlersOf methods, "*" may be used to denote all HTTP methods for which handlers exist. When "*" is used instead of an HTTP method, all the existing HTTP method handlers of the responder are wrapped.
Router ¶
The Router type is more suitable when multiple hosts with different root domains or subdomains are needed.
import (
// ...
nm "github.com/ShohruhAdham/nanomux"
)
// --------------------------------------------------
// The resource tree:
//
// http://www.example.com ─ admin ─ console ─ news
//
// http://example.com 🠖 http://www.example.com
//
// http://news.example.com ┬ domestic
// ├ international
// └ {category}
//
// http://forecast.example.com ┬ today
// └ {numberOfDays:5|10}_days
//
// / ─ static
// --------------------------------------------------
type DataBase struct {
// ...
}
// ...
var router = nm.NewRouter()
router.SetURLHandlerFor("GET", "http://www.example.com", GetMainPage)
router.RedirectAnyRequestAt(
"http://example.com",
"http://www.example.com:8000", // The server will listen on port 8000.
http.StatusPermanentRedirect,
)
var adminResource = router.Resource("http://www.example.com/admin/")
adminResource.WrapRequestPasser(CheckCredentials)
adminResource.SetHandlerFor("GET", GetLoginPage)
adminResource.SetPathHandlerFor("GET", "console/", GetConsole)
adminResource.SetPathHandlerFor("POST", "console/news", PostNews)
var newsHost = router.Host("http://news.example.com")
newsHost.SetHandlerFor("GET", GetNews)
newsHost.SetPathHandlerFor("GET", "/domestic", GetDomesticNews)
newsHost.SetPathHandlerFor("GET", "/international", GetInternationalNews)
newsHost.SetPathHandlerFor("GET", "/{category}", GetNewsByCategory)
var forecastHost = router.Host("http://forecast.example.com")
forecastHost.SetPathHandlerFor("GET", "/today", GetTodaysForecast)
forecastHost.SetPathHandlerFor(
"GET",
"/{numberOfDays:5|10}_days",
Get5or10DaysForecast,
)
// resource path: "/static/", directory: "./static/"
var fs = NewFileServer("/static/", "./static/")
router.RegisterResource(fs)
var db = &DataBase{
// ...
}
router.SetSharedDataForAll(db)
// --------------------------------------------------
var err = http.ListenAndServe(":8000", router)
if err != nil {
// ...
}
Converting http.Handler and http.HandlerFunc ¶
It is possible to use an http.Handler and an http.HandlerFunc with NanoMux. For that, NanoMux provides four converters: Hr, HrWithArgs, FnHr, and FnHrWithArgs. The Hr and HrWithArgs convert the http.Handler, while the FnHr and FnHrWithArgs convert the function with the signature of the http.HandlerFunc to the nanomux.Handler.
Most of the time, when there is a need to use an http.Handler and http.HandlerFunc, it's to utilize the handlers written outside the context of NanoMux, and those handlers don't use the *Args argument. The Hr and FnHr converters return a handler that ignores the *Args argument instead of inserting it into the request's context, which is a slower operation. These converters must be used when the http.Handler and http.HandlerFunc handlers don't need the *Args argument. If they are written to use the *Args argument, then it's better to change their signatures as well.
One situation where http.Handler and http.HandlerFunc can be considered when writing handlers might be to use a middleware with the signature of func(http.Handler) http.Handler. But for middleware with that signature, NanoMux provides an Mw converter. The Mw converter converts the middleware with the signature of func(http.Handler) http.Handler to the middleware with the signature of func(nanomux.Handler) nanomux.Handler, so it can be used to wrap the NanoMux handlers.
func GetStats(w http.ResponseWriter, r *http.Request) {
// ...
}
func PostStats(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// ...
},
)
}
func MiddlewareWithParam(param string, next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// ...
},
)
}
// ...
var r = nanomux.NewDormantResource("stats")
r.SetHandlerFor("GET", nanomux.FnHr(GetStats))
r.SetHandlerFor("POST", PostStats)
r.WrapRequestHandler(nanomux.Mw(Middleware))
r.WrapHandlerOf(
"GET, POST",
nanomux.Mw(func(next http.Handler) http.Handler {
return MiddlewareWithParam("param", next)
}),
)
Index ¶
- Variables
- func PermanentRedirectCode() int
- func SetCommonRedirectHandler(fn RedirectHandler)
- func SetHandlerForNotFound(handler Handler)
- func SetPermanentRedirectCode(code int)
- func WrapCommonRedirectHandler(mws ...func(RedirectHandler) RedirectHandler)
- func WrapHandlerOfNotFound(mws ...Middleware)
- type Args
- func (args *Args) CurrentResource() *Resource
- func (args *Args) Get(key interface{}) interface{}
- func (args *Args) Host() *Host
- func (args *Args) HostPathValues() HostPathValues
- func (args *Args) RemainingPath() string
- func (args *Args) ResponderImpl() Impl
- func (args *Args) ResponderSharedData() interface{}
- func (args *Args) Set(key, value interface{})
- type Config
- type Handler
- type Host
- func (rb *Host) ChildResourceNamed(name string) *Resource
- func (rb *Host) ChildResources() []*Resource
- func (rb *Host) Configuration() Config
- func (rb *Host) ConfigurationAt(pathTmplStr string) Config
- func (rb *Host) HandlerOf(method string) Handler
- func (rb *Host) HandlesThePathAsIs() bool
- func (rb *Host) HasAnyChildResources() bool
- func (rb *Host) HasChildResource(r *Resource) bool
- func (rb *Host) HasTrailingSlash() bool
- func (rb *Host) Implementation() Impl
- func (rb *Host) ImplementationAt(pathTmplStr string) Impl
- func (rb *Host) IsLenientOnTrailingSlash() bool
- func (rb *Host) IsLenientOnUncleanPath() bool
- func (rb *Host) IsSecure() bool
- func (rb *Host) IsStrictOnTrailingSlash() bool
- func (rb *Host) IsSubtreeHandler() bool
- func (rb *Host) Name() string
- func (rb *Host) PathHandlerOf(method, pathTmplStr string) Handler
- func (rb *Host) PermanentRedirectCode() int
- func (rb *Host) PermanentRedirectCodeAt(pathTmplStr string) int
- func (rb *Host) RedirectAnyRequestAt(pathTmplStr, url string, redirectCode int)
- func (rb *Host) RedirectAnyRequestTo(url string, redirectCode int)
- func (rb *Host) RedirectHandler() RedirectHandler
- func (rb *Host) RedirectHandlerAt(pathTmplStr string) RedirectHandler
- func (rb *Host) RedirectRequestAt(pathTmplStr, url string, redirectCode int)
- func (rb *Host) RedirectRequestTo(url string, redirectCode int)
- func (rb *Host) RedirectsInsecureRequest() bool
- func (rb *Host) RegisterResource(r *Resource)
- func (rb *Host) RegisterResourceUnder(prefixPath string, r *Resource)
- func (rb *Host) RegisteredResource(pathTmplStr string) *Resource
- func (rb *Host) Resource(pathTmplStr string) *Resource
- func (rb *Host) ResourceUsingConfig(pathTmplStr string, config Config) *Resource
- func (rb *Host) Router() *Router
- func (hb *Host) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rb *Host) SetConfiguration(config Config)
- func (rb *Host) SetConfigurationAt(pathTmplStr string, config Config)
- func (rb *Host) SetConfigurationForSubtree(config Config)
- func (rb *Host) SetHandlerFor(methods string, handler Handler)
- func (rb *Host) SetImplementation(impl Impl)
- func (rb *Host) SetImplementationAt(pathTmplStr string, rh Impl)
- func (rb *Host) SetPathHandlerFor(methods, pathTmplStr string, handler Handler)
- func (rb *Host) SetPermanentRedirectCode(code int)
- func (rb *Host) SetPermanentRedirectCodeAt(pathTmplStr string, code int)
- func (rb *Host) SetRedirectHandler(handler RedirectHandler)
- func (rb *Host) SetRedirectHandlerAt(pathTmplStr string, handler RedirectHandler)
- func (rb *Host) SetSharedData(data interface{})
- func (rb *Host) SetSharedDataAt(pathTmplStr string, data interface{})
- func (rb *Host) SetSharedDataForSubtree(data interface{})
- func (rb *Host) SharedData() interface{}
- func (rb *Host) SharedDataAt(pathTmplStr string) interface{}
- func (rb *Host) Template() *Template
- func (rb *Host) URL(values HostPathValues) (*url.URL, error)
- func (rb *Host) WrapHandlerOf(methods string, mws ...Middleware)
- func (rb *Host) WrapPathHandlerOf(methods, pathTmplStr string, mws ...Middleware)
- func (rb *Host) WrapRedirectHandler(mws ...func(RedirectHandler) RedirectHandler)
- func (rb *Host) WrapRedirectHandlerAt(pathTmplStr string, mws ...func(RedirectHandler) RedirectHandler)
- func (rb *Host) WrapRequestHandler(mws ...Middleware)
- func (rb *Host) WrapRequestHandlerAt(pathTmplStr string, mws ...Middleware)
- func (rb *Host) WrapRequestPasser(mws ...Middleware)
- func (rb *Host) WrapRequestPasserAt(pathTmplStr string, mws ...Middleware)
- func (rb *Host) WrapSubtreeHandlersOf(methods string, mws ...Middleware)
- func (rb *Host) WrapSubtreeRequestHandlers(mws ...Middleware)
- func (rb *Host) WrapSubtreeRequestPassers(mws ...Middleware)
- type HostPathValues
- type Impl
- type Middleware
- type RedirectHandler
- type Resource
- func (rb *Resource) ChildResourceNamed(name string) *Resource
- func (rb *Resource) ChildResources() []*Resource
- func (rb *Resource) Configuration() Config
- func (rb *Resource) ConfigurationAt(pathTmplStr string) Config
- func (rb *Resource) HandlerOf(method string) Handler
- func (rb *Resource) HandlesThePathAsIs() bool
- func (rb *Resource) HasAnyChildResources() bool
- func (rb *Resource) HasChildResource(r *Resource) bool
- func (rb *Resource) HasTrailingSlash() bool
- func (rb *Resource) Host() *Host
- func (rb *Resource) Implementation() Impl
- func (rb *Resource) ImplementationAt(pathTmplStr string) Impl
- func (rb *Resource) IsLenientOnTrailingSlash() bool
- func (rb *Resource) IsLenientOnUncleanPath() bool
- func (rb *Resource) IsSecure() bool
- func (rb *Resource) IsStrictOnTrailingSlash() bool
- func (rb *Resource) IsSubtreeHandler() bool
- func (rb *Resource) Name() string
- func (rb *Resource) Parent() *Resource
- func (rb *Resource) PathHandlerOf(method, pathTmplStr string) Handler
- func (rb *Resource) PermanentRedirectCode() int
- func (rb *Resource) PermanentRedirectCodeAt(pathTmplStr string) int
- func (rb *Resource) RedirectAnyRequestAt(pathTmplStr, url string, redirectCode int)
- func (rb *Resource) RedirectAnyRequestTo(url string, redirectCode int)
- func (rb *Resource) RedirectHandler() RedirectHandler
- func (rb *Resource) RedirectHandlerAt(pathTmplStr string) RedirectHandler
- func (rb *Resource) RedirectRequestAt(pathTmplStr, url string, redirectCode int)
- func (rb *Resource) RedirectRequestTo(url string, redirectCode int)
- func (rb *Resource) RedirectsInsecureRequest() bool
- func (rb *Resource) RegisterResource(r *Resource)
- func (rb *Resource) RegisterResourceUnder(prefixPath string, r *Resource)
- func (rb *Resource) RegisteredResource(pathTmplStr string) *Resource
- func (rb *Resource) Resource(pathTmplStr string) *Resource
- func (rb *Resource) ResourceUsingConfig(pathTmplStr string, config Config) *Resource
- func (rb *Resource) Router() *Router
- func (rb *Resource) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rb *Resource) SetConfiguration(config Config)
- func (rb *Resource) SetConfigurationAt(pathTmplStr string, config Config)
- func (rb *Resource) SetConfigurationForSubtree(config Config)
- func (rb *Resource) SetHandlerFor(methods string, handler Handler)
- func (rb *Resource) SetImplementation(impl Impl)
- func (rb *Resource) SetImplementationAt(pathTmplStr string, rh Impl)
- func (rb *Resource) SetPathHandlerFor(methods, pathTmplStr string, handler Handler)
- func (rb *Resource) SetPermanentRedirectCode(code int)
- func (rb *Resource) SetPermanentRedirectCodeAt(pathTmplStr string, code int)
- func (rb *Resource) SetRedirectHandler(handler RedirectHandler)
- func (rb *Resource) SetRedirectHandlerAt(pathTmplStr string, handler RedirectHandler)
- func (rb *Resource) SetSharedData(data interface{})
- func (rb *Resource) SetSharedDataAt(pathTmplStr string, data interface{})
- func (rb *Resource) SetSharedDataForSubtree(data interface{})
- func (rb *Resource) SharedData() interface{}
- func (rb *Resource) SharedDataAt(pathTmplStr string) interface{}
- func (rb *Resource) Template() *Template
- func (rb *Resource) URL(values HostPathValues) (*url.URL, error)
- func (rb *Resource) WrapHandlerOf(methods string, mws ...Middleware)
- func (rb *Resource) WrapPathHandlerOf(methods, pathTmplStr string, mws ...Middleware)
- func (rb *Resource) WrapRedirectHandler(mws ...func(RedirectHandler) RedirectHandler)
- func (rb *Resource) WrapRedirectHandlerAt(pathTmplStr string, mws ...func(RedirectHandler) RedirectHandler)
- func (rb *Resource) WrapRequestHandler(mws ...Middleware)
- func (rb *Resource) WrapRequestHandlerAt(pathTmplStr string, mws ...Middleware)
- func (rb *Resource) WrapRequestPasser(mws ...Middleware)
- func (rb *Resource) WrapRequestPasserAt(pathTmplStr string, mws ...Middleware)
- func (rb *Resource) WrapSubtreeHandlersOf(methods string, mws ...Middleware)
- func (rb *Resource) WrapSubtreeRequestHandlers(mws ...Middleware)
- func (rb *Resource) WrapSubtreeRequestPassers(mws ...Middleware)
- type Router
- func (ro *Router) ConfigurationAt(urlTmplStr string) Config
- func (ro *Router) HasAnyHost() bool
- func (ro *Router) HasHost(h *Host) bool
- func (ro *Router) Host(hostTmplStr string) *Host
- func (ro *Router) HostNamed(name string) *Host
- func (ro *Router) HostUsingConfig(hostTmplStr string, config Config) *Host
- func (ro *Router) Hosts() []*Host
- func (ro *Router) ImplementationAt(urlTmplStr string) Impl
- func (ro *Router) PermanentRedirectCodeAt(urlTmplStr string) int
- func (ro *Router) RedirectAnyRequestAt(urlTmplStr, url string, redirectCode int)
- func (ro *Router) RedirectHandlerAt(urlTmplStr string) RedirectHandler
- func (ro *Router) RedirectRequestAt(urlTmplStr, url string, redirectCode int)
- func (ro *Router) RegisterHost(h *Host)
- func (ro *Router) RegisterResource(r *Resource)
- func (ro *Router) RegisterResourceUnder(urlTmplStr string, r *Resource)
- func (ro *Router) RegisteredHost(hostTmplStr string) *Host
- func (ro *Router) RegisteredResource(urlTmplStr string) *Resource
- func (ro *Router) Resource(urlTmplStr string) *Resource
- func (ro *Router) ResourceUsingConfig(urlTmplStr string, config Config) *Resource
- func (ro *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (ro *Router) SetConfigurationAt(urlTmplStr string, config Config)
- func (ro *Router) SetConfigurationForAll(config Config)
- func (ro *Router) SetImplementationAt(urlTmplStr string, impl Impl)
- func (ro *Router) SetPermanentRedirectCodeAt(urlTmplStr string, code int)
- func (ro *Router) SetRedirectHandlerAt(urlTmplStr string, handler RedirectHandler)
- func (ro *Router) SetSharedDataAt(urlTmplStr string, data interface{})
- func (ro *Router) SetSharedDataForAll(data interface{})
- func (ro *Router) SetURLHandlerFor(methods string, urlTmplStr string, handler Handler)
- func (ro *Router) SharedDataAt(urlTmplStr string) interface{}
- func (ro *Router) URLHandlerOf(method string, urlTmplStr string) Handler
- func (ro *Router) WrapAllHandlersOf(methods string, mws ...Middleware)
- func (ro *Router) WrapAllRequestHandlers(mws ...Middleware)
- func (ro *Router) WrapAllRequestPassers(mws ...Middleware)
- func (ro *Router) WrapRedirectHandlerAt(urlTmplStr string, mws ...func(RedirectHandler) RedirectHandler)
- func (ro *Router) WrapRequestHandlerAt(urlTmplStr string, mws ...Middleware)
- func (ro *Router) WrapRequestPasser(mws ...Middleware)
- func (ro *Router) WrapRequestPasserAt(urlTmplStr string, mws ...Middleware)
- func (ro *Router) WrapURLHandlerOf(methods string, urlTmplStr string, mws ...Middleware)
- type Similarity
- type Template
- func (t *Template) Apply(values TemplateValues, ignoreMissing bool) string
- func (t *Template) Clear()
- func (t *Template) Content() string
- func (t *Template) HasPattern() bool
- func (t *Template) HasValueName(names ...string) bool
- func (t *Template) IsStatic() bool
- func (t *Template) IsWildcard() bool
- func (t *Template) Match(str string, values TemplateValues) (bool, TemplateValues)
- func (t *Template) Name() string
- func (t *Template) SetName(name string)
- func (t *Template) SimilarityWith(t2 *Template) Similarity
- func (t *Template) String() string
- func (t *Template) TryToApply(values TemplateValues, ignoreMissing bool) (string, error)
- func (t *Template) UnescapedContent() string
- func (t *Template) ValueNames() []string
- type TemplateValues
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidTemplate is returned when a template is empty or not complete. ErrInvalidTemplate = fmt.Errorf("invalid template") // ErrInvalidValue is returned from the Template's Apply method when one of // the values doesn't match the pattern. ErrInvalidValue = fmt.Errorf("invalid value") // ErrMissingValue is returned from the Template's Apply method when one of // the values is missing. ErrMissingValue = fmt.Errorf("missing value") // ErrDifferentPattern is returned when a different pattern is provided for // the repeated value name. ErrDifferentPattern = fmt.Errorf("different pattern") // ErrRepeatedWildcardName is returned when the wildcard name comes again in // the template. ErrRepeatedWildcardName = fmt.Errorf("repeated wild card name") // ErrAnotherWildcardName is returned when there is more than one wildcard // name in the template. ErrAnotherWildcardName = fmt.Errorf("another wild card name") // Template similarity errors. ErrDifferentTemplates = fmt.Errorf("different templates") ErrDifferentValueNames = fmt.Errorf("different value names") ErrDifferentNames = fmt.Errorf("different names") )
Template errors.
Functions ¶
func PermanentRedirectCode ¶
func PermanentRedirectCode() int
PermanentRedirectCode returns the status code for permanent redirects. The code is used to redirect requests to an "https" from an "http", to a URL with a trailing slash from a URL without, or vice versa. It's either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
Responders may have their own permanent redirect status code.
func SetCommonRedirectHandler ¶
func SetCommonRedirectHandler(fn RedirectHandler)
SetCommonRedirectHandler can be used to set a custom implementation of the common redirect handler function.
The handler is mostly used to redirect requests to an "https" from an "http", to a URL with a trailing slash from a URL without, or vice versa. It's also used when responders have been configured to redirect requests to a new location.
Responders may have their own redirect handler set.
func SetHandlerForNotFound ¶
func SetHandlerForNotFound(handler Handler)
SetHandlerForNotFound can be used to set a custom handler for not-found resources.
func SetPermanentRedirectCode ¶
func SetPermanentRedirectCode(code int)
SetPermanentRedirectCode sets the status code for permanent redirects. It's used to redirect requests to an "https" from an "http", to a URL with a trailing slash from one without, or vice versa. The code is either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
Responders may have their own permanent redirect status code set.
func WrapCommonRedirectHandler ¶
func WrapCommonRedirectHandler( mws ...func(RedirectHandler) RedirectHandler, )
WrapCommonRedirectHandler wraps the common redirect handler with middlewares in their passed order.
This function can be used when the handler's default implementation is sufficient and only the response headers need to be changed, or some other additional functionality is required.
The redirect handler is mostly used to redirect requests to an "https" from an "http", to a URL with a trailing slash from a URL without, or vice versa. It's also used when responders have been configured to redirect requests to a new location.
func WrapHandlerOfNotFound ¶
func WrapHandlerOfNotFound(mws ...Middleware)
WrapHandlerOfNotFound wraps the handler of not-found resources with middlewares in their passed order. This function can be used when the handler's default implementation is sufficient but additional functionality is required.
Types ¶
type Args ¶
type Args struct {
// contains filtered or unexported fields
}
Args is created for each request and passed to handlers. The middleware must pass the *Args argument to the next handler.
func ArgsFrom ¶
ArgsFrom is a function to retrieve the argument *Args in the http.Handler or http.HandlerFunc after the conversion to the Handler with the HrWithArgs or FnHrWithArgs functions.
func (*Args) CurrentResource ¶
CurrentResource returns the current resource that is passing or handling the request. If the request is being handled by a host, nil is returned. In that case, the Host method must be used.
func (*Args) Get ¶
func (args *Args) Get(key interface{}) interface{}
Get returns the custom argument that was set with the Set method.
func (*Args) Host ¶
Host returns the *Host of the responders' tree, to which the request's URL maps. If the tree doesn't have a *Host, nil is returned.
func (*Args) HostPathValues ¶
func (args *Args) HostPathValues() HostPathValues
HostPathValues returns the host and path values of the request's URL.
func (*Args) RemainingPath ¶
RemainingPath returns the escaped remaining path of the request's URL that's below the responder's segment that is currently passing or handling the request.
func (*Args) ResponderImpl ¶
ResponderImpl returns the implementation of the host or resource that is currently handling the request. If the host or resource wasn't created from an Impl or if they have no Impl set, nil is returned.
func (*Args) ResponderSharedData ¶
func (args *Args) ResponderSharedData() interface{}
ResponderSharedData returns the shared data of the host or resource that is currently handling the request. If the shared data wasn't set, nil is returned.
func (*Args) Set ¶
func (args *Args) Set(key, value interface{})
Set sets the custom argument that is passed between middlewares and/or handlers. The rules for defining a key are the same as in the context package. The key must be comparable and its type must be custom defined. The recommended type is an empty struct (struct{}) to avoid allocation when assigning to an interface{}. As stated in the context package, exported key variables' static type should be a pointer or interface.
type Config ¶
type Config struct {
// SubtreeHandler means that a host or resource can handle a request when
// there is no child resource in the subtree with the matching template to
// handle the request's path segment. The remaining path can be retrieved
// from the *Args argument with the RemainingPathKey method.
SubtreeHandler bool
// Secure means that a host or resource can be available only under https.
Secure bool
// RedirectsInsecureRequest means that a responder redirects the request
// from an insecure endpoint to a secure one, i.e., from http to https,
// instead of responding with a "404 Not Found" status code.
RedirectsInsecureRequest bool
// HasTrailingSlash means that a responder has a trailing slash in its URL.
// If a request is made to a URL without a trailing slash, the resource
// redirects it to a URL with a trailing slash.
HasTrailingSlash bool
// StrictOnTrailingSlash tells the resource to drop the request when the
// presence or absence of the trailing slash in the request's URL doesn't
// match the resource's. By default, resources redirect requests to the
// matching version of the URL.
StrictOnTrailingSlash bool
// LenientOnTrailingSlash allows the responder to respond, ignoring the
// fact of the presence or absence of the trailing slash in the request's
// URL. By default, responders redirect requests to the matching version of
// the URL.
LenientOnTrailingSlash bool
// LenientOnUncleanPath allows the responder to respond, ignoring unclean
// paths, i.e. paths with empty path segments or containing dot segments.
// By default, reponders redirect requests to the clean version of the URL.
//
// When used with a non-subtree host, the LenientOnUncleanPath property has
// no effect.
LenientOnUncleanPath bool
// HandlesThePathAsIs can be used to set both the LenientOnTrailingSlash
// and the LenientOnUncleanPath at the same time.
HandlesThePathAsIs bool
}
Config contains the configuration properties of the responder. At construction, the scheme and trailing slash properties are configured from the resource's URL. For example, with the URL "https://example.com/resource/", Config's Secure and TrailingSlash properties are set to true. This makes the responder, unless configured differently with other properties, ignore the request when the connection is not over "https" and redirect the request when its URL does not end with a trailing slash.
In NanoMux, the Host type responds to the request instead of the root resource. This eliminates the need to create a root resource and register it under the host. As the path must contain at least a single slash "/", properties related to a trailing slash cannot be applied to a host. But, the host can be configured with them. They will be used for the last path segment, when the host is a subtree handler and must respond to the request.
type Handler ¶
Handler is the type of function used for handling HTTP requests depending on their HTTP method.
func FnHr ¶
func FnHr(hf http.HandlerFunc) Handler
FnHr converts an http.HandlerFunc to a nanomux.Handler. FnHr must be used when the htpt.HandlerFunc doesn't need an *Args argument.
func FnHrWithArgs ¶
func FnHrWithArgs(hf http.HandlerFunc) Handler
FnHrWithArgs converts an http.HandlerFunc to a nanomux.Handler. FnHrWithArgs returns a handler that inserts the *Args argument into the request's context. The *Args argument can be retrieved from the request with the ArgsFrom function.
When the http.HandlerFunc doesn't use the *Args argument, then the FnHr converter must be used instead. Because the handler returned from the FnHr converter is comparatively faster.
func HandlerOfNotFound ¶
func HandlerOfNotFound() Handler
HandlerOfNotFound returns the handler of not-found resources.
func Hr ¶
Hr converts an http.Handler to a nanomux.Handler. Hr must be used when the http.Handler doesn't need an *Args argument.
func HrWithArgs ¶
HrWithArgs converts an http.Handler to a nanomux.Handler. HrWithArgs returns a handler that inserts the *Args argument into the request's context. The *Args argument can be retrieved from the request with the ArgsFrom function.
When the http.Handler doesn't use the *Args argument, then the Hr converter must be used instead. Because the handler returned from the Hr converter is comparatively faster.
type Host ¶
type Host struct {
// contains filtered or unexported fields
}
Host represents the host component as a resource. When the Host type is used, there is no need for a root resource. When HTTP method handlers are set, the host responds to the requests made to the root path.
func NewDormantHost ¶
NewDormantHost returns a new dormant host (without HTTP method handlers).
The template's scheme and trailing slash values are used to configure the host. The trailing slash is used only for the last path segment when the host is a subtree handler and should respond to the request. It has no effect on the host itself. The template cannot be a wildcard template.
func NewDormantHostUsingConfig ¶
NewDormantHostUsingConfig returns a new dormant host (without HTTP method hanlders).
The host is configured with the properties in the config as well as the scheme and trailing slash values of the host template. The trailing slash is used only for the last path segment when the host is a subtree handler and should respond to the request. It has no effect on the host itself. The config's Secure and TrailingSlash values are ignored and may not be set. The host template cannot be a wildcard template.
func NewHost ¶
NewHost returns a new host.
The template's scheme and trailing slash values are used to configure the host. The trailing slash is used only for the last path segment when the host is a subtree handler and should respond to the request. It has no effect on the host itself. The template cannot be a wildcard template.
The Impl is, in a sense, the implementation of the host. It is an instance of a type with methods to handle HTTP requests. Methods must have the signature of the Handler and must start with the "Handle" prefix. The remaining part of any such method's name is considered an HTTP method. For example, HandleGet and HandleShare are considered the handlers of the GET and SHARE HTTP methods, respectively. If the value of the impl has the HandleNotAllowedMethod method, then it's used as the handler of the not allowed HTTP methods.
Example:
type ExampleHost struct{}
func (eh *ExampleHost) HandleGet(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// ...
var exampleHost = NewHost("https://example.com", &ExampleHost{})
func NewHostUsingConfig ¶
NewHostUsingConfig returns a new host.
The host is configured with the properties in the config as well as the scheme and trailing slash values of the host template. The trailing slash is used only for the last path segment when the host is a subtree handler and should respond to the request. It has no effect on the host itself. The config's Secure and TrailingSlash values are ignored and may not be set. The host template cannot be a wildcard template.
The Impl is, in a sense, the implementation of the host. It is an instance of a type with methods to handle HTTP requests. Methods must have the signature of the Handler and must start with the "Handle" prefix. The remaining part of any such method's name is considered an HTTP method. For example, HandleGet and HandleShare are considered the handlers of the GET and SHARE HTTP methods, respectively. If the value of the impl has the HandleNotAllowedMethod method, then it's used as the handler of the not allowed HTTP methods.
Example:
type ExampleHost struct{}
func (eh *ExampleHost) HandleGet(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// ...
var exampleHost = NewHostUsingConfig(
"https://example.com",
&ExampleHost{},
Config{SubtreeHandler: true, RedirectInsecureRequest: true},
)
func (*Host) ChildResourceNamed ¶
ChildResourceNamed returns the named resource if it exists, otherwise it returns nil. Only the direct child resources of the responder will be looked at.
func (*Host) ChildResources ¶
func (rb *Host) ChildResources() []*Resource
ChildResources returns all the child resources of the responder. If the responder doesn't have any child resources, the method returns nil.
func (*Host) Configuration ¶
func (rb *Host) Configuration() Config
Configuration returns the configuration of responder.
func (*Host) ConfigurationAt ¶
ConfigurationAt returns the configuration of the existing resource at the path.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
func (*Host) HandlerOf ¶
HandlerOf returns the HTTP method handler of the responder. If the handler doesn't exist, nil is returned.
The argument method is an HTTP method. An exclamation mark "!" can be used to get the not allowed HTTP method handler. Examples: "GET", "POST" or "!".
func (*Host) HandlesThePathAsIs ¶
func (rb *Host) HandlesThePathAsIs() bool
HandlesThePathAsIs returns true if the responder was configured to be lenient on both, trailing slash and unclean paths.
func (*Host) HasAnyChildResources ¶
func (rb *Host) HasAnyChildResources() bool
HasAnyChildResources returns true if the responder has any child resources.
func (*Host) HasChildResource ¶
HasChildResource returns true if the argument resource is a direct child of the responder.
func (*Host) HasTrailingSlash ¶
func (rb *Host) HasTrailingSlash() bool
HasTrailingSlash returns true if the responder's URL ends with a trailing slash. If the responder has a trailing slash in its URL and the request is made to the URL without a trailing slash, the responder redirects it to the URL with a trailing slash and vice versa.
func (*Host) Implementation ¶
func (rb *Host) Implementation() Impl
Implementation returns the implementation of the responder. If the responder wasn't created from an Impl or if it has no Impl set, nil is returned.
func (*Host) ImplementationAt ¶
ImplementationAt returns the implementation of the existing resource at the path. If the resource wasn't created from an Impl or it has no Impl set, nil is returned.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
func (*Host) IsLenientOnTrailingSlash ¶
func (rb *Host) IsLenientOnTrailingSlash() bool
IsLenientOnTrailingSlash returns true if the responder was configured to ignore an unmatched trailing slash in the request's URL.
func (*Host) IsLenientOnUncleanPath ¶
func (rb *Host) IsLenientOnUncleanPath() bool
IsLenientOnUncleanPath returns true if the responder was configured to ignore unclean paths like "example.com///.//resource1//resource2".
func (*Host) IsSecure ¶
func (rb *Host) IsSecure() bool
IsSecure returns true if the responder was configured to respond only if it is used under HTTPS.
func (*Host) IsStrictOnTrailingSlash ¶
func (rb *Host) IsStrictOnTrailingSlash() bool
IsStrictOnTrailingSlash returns true if the responder was configured to drop the request when the presence or absence of the trailing slash in the request's URL doesn't match with its own URL. By default, the responder redirects the request on unmatched trailing slash.
func (*Host) IsSubtreeHandler ¶
func (rb *Host) IsSubtreeHandler() bool
IsSubtreeHandler returns true if the responder was configured to be a subtree handler.
func (*Host) Name ¶
func (rb *Host) Name() string
Name returns the name of the responder given in the template.
func (*Host) PathHandlerOf ¶
PathHandlerOf returns the HTTP method handler of the existing resource at the path.If the handler doesn't exist, nil is returned.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The argument method is an HTTP method. An exclamation mark "!" can be used to get the not allowed HTTP method handler. Examples: "GET", "POST" or "!".
func (*Host) PermanentRedirectCode ¶
func (rb *Host) PermanentRedirectCode() int
PermanentRedirectCode returns the responder's status code for permanent redirects. The code is used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. It's either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Host) PermanentRedirectCodeAt ¶
PermanentRedirectCodeAt returns the status code of the existing resource at the path for permanent redirects.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The code is used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. It's either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Host) RedirectAnyRequestAt ¶
RedirectAnyRequestAt configures the resource at the path to redirect requests to another URL. Requests made to the resource or its subtree will all be redirected. Neither the request passer nor the request handler of the resource will be called. Subtree resources specified in the request's URL are not required to exist. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The RedirectAnyRequestAt method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the resource is configured properly.
Example:
var host = NewDormantHost("http://example.com")
host.RedirectAnyRequestAt(
"/simulation",
"http://example.com/reality",
http.StatusMovedPermanently,
)
func (*Host) RedirectAnyRequestTo ¶
RedirectAnyRequestTo configures the responder to redirect requests to another URL. Requests made to the responder or its subtree will all be redirected. Neither the request passer nor the request handler of the responder will be called. Subtree resources specified in the request's URL are not required to exist. If the responder doesn't exist, it will be created.
The RedirectAnyRequstTo method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the responder is configured properly.
Example:
var host = NewDormantHost("http://example.com")
host.RedirectAnyRequestTo(
"http://www.example.com",
http.StatusPermanentRedirect,
)
func (*Host) RedirectHandler ¶
func (rb *Host) RedirectHandler() RedirectHandler
RedirectHandler returns the redirect handler function of the responder.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the responder has been configured to redirect requests to a new location.
func (*Host) RedirectHandlerAt ¶
func (rb *Host) RedirectHandlerAt( pathTmplStr string, ) RedirectHandler
RedirectHandlerAt returns the redirect handler function of the existing resource at the path.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the resource has been configured to redirect requests to a new location.
func (*Host) RedirectRequestAt ¶
RedirectRequestAt configures the resource at the path to redirect requests to another URL. The request handler of the resource won't be called. If the resource is a subtree handler and there is no resource in its subtree to handle a request, the resource redirects the request to the URL, adding the remaining path segments to it. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The RedirectRequestAt method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the resource is configured properly.
Example:
var root = NewDormantResource("https:///")
root.RedirectRequestAt(
"https:///simulation",
"https:///reality",
http.StatusMovedPermanently,
)
func (*Host) RedirectRequestTo ¶
RedirectRequestTo configures the responder to redirect requests to another URL. The request handler of the responder won't be called. If the responder is a subtree handler and there is no resource in its subtree to handle a request, the responder redirects the request to the URL, adding the remaining path segments to it. If the responder doesn't exist, it will be created.
The RedirectRequstTo method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the responder is configured properly.
Example:
var root = NewDormantResource("https:///")
root.RedirectRequestTo(
"https:///login",
http.StatusPermanentRedirect,
)
func (*Host) RedirectsInsecureRequest ¶
func (rb *Host) RedirectsInsecureRequest() bool
RedirectsInsecureRequest returns true if the responder was configured to redirect insecure requests, instead of responding with a "404 Not Found" status code.
The responder can be configured to redirect insecure requests if it's intended to be used in both HTTP and HTTPS servers.
func (*Host) RegisterResource ¶
func (rb *Host) RegisterResource(r *Resource)
RegisterResource registers the argument resource below in the tree of the responder.
If the argument resource has a URL template, its corresponding host and path segments must be compatible with the templates of the host and path segment resources above in the tree. The remaining path segments are used as the prefix path segments of the argument resource below the responder. If there are compatible resources with the remaining path segments below the responder, the argument resource will be registered under them. Otherwise, new resources will be created for the missing path segments.
If the argument resource's template collides with the template of one of its siblings, RegisterResource checks which one has the HTTP method handlers set and passes the other one's child resources to it. If both can handle a request, the method panics. Child resources are also checked recursively.
func (*Host) RegisterResourceUnder ¶
RegisterResourceUnder registers the argument resource below the responder and the prefix path segments.
If the argument resource has a URL template, its host and path segment templates must be compatible with the corresponding host and path segment resources in the tree and with the argument prefix path segments. If there are existing resources compatible with the prefix path segments, the argument resource will be registered under them, otherwise new resources will be created for the missing segments.
If the prefix path segment resources exist and the argument resource's template collides with the last prefix resource's child resource, RegisterResourceUnder checks which one has the HTTP method handlers set and passes the other one's child resources to it. If both can handle a request, the method panics.
The trailing slash in the prefix path is ignored.
func (*Host) RegisteredResource ¶
RegisteredResource returns the resource in the tree below the responder if it can be reached with the path template. In the path template, names can be used instead of the complete segment templates.
For example,
/childResourceTemplate/$someName/anotherResourceTemplate/, https:///$childResourceName/$grandChildResourceName
The scheme and trailing slash properties must be compatible with the resource's.
func (*Host) Resource ¶
Resource uses the path template to find an existing resource or to create a new one below in the tree of the responder and returns it. If the path template contains prefix segments that don't have existing resources, the method also creates new resources for them.
If the resource exists, its scheme and trailing slash properties are compared to the values given in the path template. They must match. If the method creates a new resource, its scheme and trailing slash properties are configured using the values given within the path template.
The names given to the path segment resources must be unique in the path and among their respective siblings.
func (*Host) ResourceUsingConfig ¶
ResourceUsingConfig uses the path template and config to find an existing resource or to create a new one below in the tree of the responder and returns it. If the path template contains prefix segments that don't have existing resources, the method also creates new resources for them.
If the resource exists, its configuration is compared to the argument config. Also, its scheme and trailing slash properties are compared to the values given in the path template. The configuration, scheme, and trailing slash properties must match. If the method creates a new resource, it's configured using the config and the values given in the path template.
The names of the path segment resources must be unique within the path and among their respective siblings.
func (*Host) ServeHTTP ¶
func (hb *Host) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the Host's implementation of the http.Handler interface. It is called when the host is used directly.
func (*Host) SetConfiguration ¶
func (rb *Host) SetConfiguration(config Config)
SetConfiguration sets the config for the responder. If the responder has been configured before, it's reconfigured, but the responder's security and trailing slash properties are not affected if they were set to true. In other words, if the responder has been configured to be secure or to have a trailing slash, these properties can't be changed. If the passed config has Secure and/or RedirectsInsecureRequest and/or TrailingSlash fields set to true, the responder's security and trailing slash properties will be set to true, respectively. Please note that, unlike during construction, if the config's RedirectsInsecureRequest field is set to true, the responder will also be configured to be secure, even if it wasn't before. The secure responders only respond when used over HTTPS.
func (*Host) SetConfigurationAt ¶
SetConfigurationAt sets the config for the resource at the path. If the resource doesn't exist, it will be created. If the existing resource has been configured before, it's reconfigured, but the resource's security and trailing slash properties are not affected if they were set to true. In other words, if the resource has been configured to be secure or to have a trailing slash, these properties can't be changed. If the passed config has Secure and/or RedirectsInsecureRequest and/or TrailingSlash fields set to true, the resource's security and trailing slash properties will be set to true, respectively. Please note that, unlike during construction, if the config's RedirectsInsecureRequest field is set to true, the resource will also be configured to be secure, even if it wasn't before. The secure resources only respond when used over HTTPS.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template as well as in the config. The config's Secure and TrailingSlash values are ignored when creating a new resource.
func (*Host) SetConfigurationForSubtree ¶
func (rb *Host) SetConfigurationForSubtree(config Config)
SetConfigurationForSubtree sets the config for all the resources in the subtree, but the resources' security and trailing slash properties are not affected if they were set to true. If the resources are configured with properties other than security and trailing slash, those resources will be skipped.
func (*Host) SetHandlerFor ¶
SetHandlerFor sets the handler function as a request handler for the HTTP methods.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method and must be used alone. That is, setting the not allowed HTTP method handler must happen in a separate call. Examples of methods: "GET", "PUT, POST", "SHARE, LOCK" or "!".
func (*Host) SetImplementation ¶
func (rb *Host) SetImplementation(impl Impl)
SetImplementation sets the HTTP method handlers from the passed impl. The impl is also kept for future retrieval. All existing handlers are discarded.
func (*Host) SetImplementationAt ¶
SetImplementationAt sets the HTTP method handlers for a resource at the path from the passed Impl's methods. If the resource doesn't exist, the method creates it. The resource keeps the impl for future retrieval. Old handlers of the existing resource are discarded.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
func (*Host) SetPathHandlerFor ¶
SetPathHandlerFor sets the HTTP methods' handler function for a resource at the path. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method and must be used alone. That is, setting the not allowed HTTP method handler must happen in a separate call. Examples of methods: "GET", "PUT, POST", "SHARE, LOCK" or "!".
func (*Host) SetPermanentRedirectCode ¶
func (rb *Host) SetPermanentRedirectCode(code int)
SetPermanentRedirectCode sets the status code for permanent redirects. It's used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. The code is either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Host) SetPermanentRedirectCodeAt ¶
SetPermanentRedirectCodeAt sets the status code of the resource at the path for permanent redirects. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The status code is sent when redirecting the request to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. The code is either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Host) SetRedirectHandler ¶
func (rb *Host) SetRedirectHandler(handler RedirectHandler)
SetRedirectHandler can be used to set a custom implementation of the redirect handler function.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the responder has been configured to redirect requests to a new location.
func (*Host) SetRedirectHandlerAt ¶
func (rb *Host) SetRedirectHandlerAt( pathTmplStr string, handler RedirectHandler, )
SetRedirectHandlerAt can be used to set a custom implementation of the redirect handler for a resource at the path. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the resource has been configured to redirect requests to a new location.
func (*Host) SetSharedData ¶
func (rb *Host) SetSharedData(data interface{})
SetSharedData sets the data shared between handlers. It's useful when the responder wasn't created from an implementation.
Shared data can be retrieved using the *Args arguments ResponderSharedData method. If the shared data can be modified, accessing it must be synchronized with a mutex or some other synchronization method.
Example:
type SharedData struct {
*sync.Mutex // Must be initilized.
X SomeType
}
...
func SomeHandler(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) {
var sharedData = args.ResponderSharedData().(*SharedData)
sharedData.Lock()
defer sharedData.Unlock()
sharedData.X = someValue
...
}
func (*Host) SetSharedDataAt ¶
func (rb *Host) SetSharedDataAt( pathTmplStr string, data interface{}, )
SetSharedDataAt sets the shared data for the resource at the path. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
func (*Host) SetSharedDataForSubtree ¶
func (rb *Host) SetSharedDataForSubtree(data interface{})
SetSharedDataForSubtree sets the shared data for each resource in the subtree that has no shared data set yet.
func (*Host) SharedData ¶
func (rb *Host) SharedData() interface{}
SharedData returns the data set by SetSharedData.
func (*Host) SharedDataAt ¶
func (rb *Host) SharedDataAt(pathTmplStr string) interface{}
SharedDataAt returns the shared data of the existing resource at the path. If the shared data wasn't set, nil is returned.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
func (*Host) Template ¶
func (rb *Host) Template() *Template
Template returns the parsed template of the responder.
func (*Host) URL ¶
func (rb *Host) URL(values HostPathValues) (*url.URL, error)
URL returns the responder's URL with values applied to it.
func (*Host) WrapHandlerOf ¶
func (rb *Host) WrapHandlerOf(methods string, mws ...Middleware)
WrapHandlerOf wraps the handlers of the HTTP methods with the middlewares in their passed order. All handlers of the HTTP methods stated in the methods argument must exist.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Host) WrapPathHandlerOf ¶
func (rb *Host) WrapPathHandlerOf( methods, pathTmplStr string, mws ...Middleware, )
WrapPathHandlerOf wraps the handlers of the HTTP methods of the existing resource at the path. The handlers are wrapped in the middlewares' passed order. All handlers of the HTTP methods stated in the methods argument must exist.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Host) WrapRedirectHandler ¶
func (rb *Host) WrapRedirectHandler( mws ...func(RedirectHandler) RedirectHandler, )
WrapRedirectHandler wraps the redirect handler function with middlewares in their passed order.
The method can be used when the handler's default implementation is sufficient and only the response headers need to be changed, or some other additional functionality is required.
The redirect handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It's also used when responder has been configured to redirect requests to a new location.
func (*Host) WrapRedirectHandlerAt ¶
func (rb *Host) WrapRedirectHandlerAt( pathTmplStr string, mws ...func(RedirectHandler) RedirectHandler, )
WrapRedirectHandlerAt wraps the redirect handler of the resource at the path. The redirect handler is wrapped in the middlewares' passed order. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The method can be used when the handler's default implementation is sufficient and only the response headers need to be changed, or some other additional functionality is required.
The redirect handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It's also used when resource has been configured to redirect requests to a new location.
func (*Host) WrapRequestHandler ¶
func (rb *Host) WrapRequestHandler(mws ...Middleware)
WrapRequestHandler wraps the responder's request handler with the middlewares in their passed order.
The request handler calls the HTTP method handler of the responder depending on the request's method. Unlike the request passer, the request handler is called only when the responder is the one to handle the request and has at least one HTTP method handler.
func (*Host) WrapRequestHandlerAt ¶
func (rb *Host) WrapRequestHandlerAt( pathTmplStr string, mws ...Middleware, )
WrapRequestHandlerAt wraps the request handler of the resource at the path. The request handler is wrapped in the middlewares' passed order. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The request handler calls the HTTP method handler of the resource depending on the request's method. Unlike the request passer, the request handler is called only when the resource is the one to handle the request and has at least one HTTP method handler.
func (*Host) WrapRequestPasser ¶
func (rb *Host) WrapRequestPasser(mws ...Middleware)
WrapRequestPasser wraps the request passer of the responder with the middlewares in their passed order.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
func (*Host) WrapRequestPasserAt ¶
func (rb *Host) WrapRequestPasserAt( pathTmplStr string, mws ...Middleware, )
WrapRequestPasserAt wraps the request passer of the resource at the path. The request passer is wrapped in the middlewares' passed order. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
func (*Host) WrapSubtreeHandlersOf ¶
func (rb *Host) WrapSubtreeHandlersOf( methods string, mws ...Middleware, )
WrapSubtreeHandlersOf wraps the HTTP method handlers of the resources in the tree below the responder.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Host) WrapSubtreeRequestHandlers ¶
func (rb *Host) WrapSubtreeRequestHandlers( mws ...Middleware, )
WrapSubtreeRequestHandlers wraps the request handlers of the resources in the tree below the responder. Handlers are wrapped in the middlewares' passed order.
The request handler calls the HTTP method handler of the responder depending on the request's method. Unlike the request passer, the request handler is called only when the responder is the one to handle the request and has at least one HTTP method handler.
func (*Host) WrapSubtreeRequestPassers ¶
func (rb *Host) WrapSubtreeRequestPassers( mws ...Middleware, )
WrapSubtreeRequestPassers wraps the request passers of the resources in the tree below the responder. The request passers are wrapped in the middlewares' passed order.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
type HostPathValues ¶
type HostPathValues = TemplateValues
HostPathValues is an alias to the TemplateValues. It contains the host and path segment values and does not include query values.
type Impl ¶
type Impl interface{}
Impl is used to accept any type that has methods to handle HTTP requests. Methods must have the signature of the Handler and start with the 'Handle' prefix. The remaining part of any such method's name is considered an HTTP method. For example, HandleGet and HandleCustom are considered the handlers of the GET and CUSTOM HTTP methods, respectively. If the type has the HandleNotAllowedMethod then it's used as the handler of the not allowed HTTB methods.
type Middleware ¶
type RedirectHandler ¶
type RedirectHandler func( w http.ResponseWriter, r *http.Request, url string, code int, args *Args, ) bool
RedirectHandler is the type of handler used for request redirecting.
func CommonRedirectHandler ¶
func CommonRedirectHandler() RedirectHandler
CommonRedirectHandler returns the common redirect handler function.
The handler is mostly used to redirect requests to an "https" from an "http", to a URL with a trailing slash from a URL without, or vice versa. It's also used when responders have been configured to redirect requests to a new location.
type Resource ¶
type Resource struct {
// contains filtered or unexported fields
}
Resource represents the path segment resource.
func NewDormantResource ¶
NewDormantResource returns a new dormant resource (without HTTP method handlers).
The template's scheme and trailing slash property values are used to configure the resource. The root resource's trailing slash property is ignored.
When the URL template contains a host and/or prefix path segment templates, the resource keeps them. Templates are used when the resource is being registered. When the resource is being registered by a router, the host and path segment templates indicate where in the tree it must be placed. When the resource is being registered by a host, the host template is checked for compatibility, and the prefix path segment templates show where in the tree the resource must be placed under the host. When the resource is being registered by another resource, the host and prefix path segment templates are checked for compatibility with the registering resource's host and corresponding prefix path segments. If there are remaining path segments that come below the registering resource, they show where in the tree the resource must be placed under the registering resource.
func NewDormantResourceUsingConfig ¶
NewDormantResourceUsingConfig returns a new dormant resource (without HTTP method handlers).
The resource is configured with the properties in the config as well as the scheme and trailing slash property values of the URL template. The config's Secure and TrailingSlash values are ignored and may not be set. The root resource's trailing slash related properties are also ignored.
When the URL template contains a host and/or prefix path segment templates, the resource keeps them. Templates are used when the resource is being registered. When the resource is being registered by a router, the host and path segment templates indicate where in the tree it must be placed. When the resource is being registered by a host, the host template is checked for compatibility, and the prefix path segment templates show where in the tree the resource must be placed under the host. When the resource is being registered by another resource, the host and prefix path segment templates are checked for compatibility with the registering resource's host and corresponding prefix path segments. If there are remaining path segments that come below the registering resource, they show where in the tree the resource must be placed under the registering resource.
func NewResource ¶
NewResource returns a new resource.
The argument URL template's scheme and trailing slash property values are used to configure the new Resource instance. The root resource's trailing slash property is ignored.
The Impl is, in a sense, the implementation of the resource. It is an instance of a type with methods to handle HTTP requests. Methods must have the signature of the Handler and must start with the "Handle" prefix. The remaining part of any such method's name is considered an HTTP method. For example, HandleGet and HandleShare are considered the handlers of the GET and SHARE HTTP methods, respectively. If the value of the impl has the HandleNotAllowedMethod method, then it's used as the handler of the not allowed HTTP methods.
Example:
type ExampleResource struct{}
func (er *ExampleResource) HandleGet(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// ...
var exampleResource = NewResource(
"https://example.com/staticTemplate/{valueName:patternTemplate}",
&ExampleResource{},
)
When the URL template contains a host and/or prefix path segment templates, the resource keeps them. Templates are used when the resource is being registered. When the resource is being registered by a router, the host and path segment templates indicate where in the tree it must be placed. When the resource is being registered by a host, the host template is checked for compatibility, and the prefix path segment templates show where in the tree the resource must be placed under the host. When the resource is being registered by another resource, the host and prefix path segment templates are checked for compatibility with the registering resource's host and corresponding prefix path segments. If there are remaining path segments that come below the registering resource, they show where in the tree the resource must be placed under the registering resource.
func NewResourceUsingConfig ¶
NewResourceUsingConfig returns a new resource.
The new Resource instance is configured with the properties in the config as well as the scheme and trailing slash property values of the URL template. The config's Secure and TrailingSlash values are ignored and may not be set. The root resource's trailing slash related properties are also ignored.
The Impl is, in a sense, the implementation of the resource. It is an instance of a type with methods to handle HTTP requests. Methods must have the signature of the Handler and must start with the "Handle" prefix. The remaining part of any such method's name is considered an HTTP method. For example, HandleGet and HandleShare are considered the handlers of the GET and SHARE HTTP methods, respectively. If the value of the impl has the HandleNotAllowedMethod method, then it's used as the handler of the not allowed HTTP methods.
Example:
type ExampleResource struct{}
func (er *ExampleResource) HandleGet(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) bool {
// ...
}
// ...
var exampleResource = NewResourceUsingConfig(
"https://example.com/{wildCardTemplate}/",
&ExampleResource{},
Config{SubtreeHandler: true, RedirectInsecureRequest: true},
)
When the URL template contains a host and/or prefix path segment templates, the resource keeps them. Templates are used when the resource is being registered. When the resource is being registered by a router, the host and path segment templates indicate where in the tree it must be placed. When the resource is being registered by a host, the host template is checked for compatibility, and the prefix path segment templates show where in the tree the resource must be placed under the host. When the resource is being registered by another resource, the host and prefix path segment templates are checked for compatibility with the registering resource's host and corresponding prefix path segments. If there are remaining path segments that come below the registering resource, they show where in the tree the resource must be placed under the registering resource.
func (*Resource) ChildResourceNamed ¶
ChildResourceNamed returns the named resource if it exists, otherwise it returns nil. Only the direct child resources of the responder will be looked at.
func (*Resource) ChildResources ¶
func (rb *Resource) ChildResources() []*Resource
ChildResources returns all the child resources of the responder. If the responder doesn't have any child resources, the method returns nil.
func (*Resource) Configuration ¶
func (rb *Resource) Configuration() Config
Configuration returns the configuration of responder.
func (*Resource) ConfigurationAt ¶
ConfigurationAt returns the configuration of the existing resource at the path.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
func (*Resource) HandlerOf ¶
HandlerOf returns the HTTP method handler of the responder. If the handler doesn't exist, nil is returned.
The argument method is an HTTP method. An exclamation mark "!" can be used to get the not allowed HTTP method handler. Examples: "GET", "POST" or "!".
func (*Resource) HandlesThePathAsIs ¶
func (rb *Resource) HandlesThePathAsIs() bool
HandlesThePathAsIs returns true if the responder was configured to be lenient on both, trailing slash and unclean paths.
func (*Resource) HasAnyChildResources ¶
func (rb *Resource) HasAnyChildResources() bool
HasAnyChildResources returns true if the responder has any child resources.
func (*Resource) HasChildResource ¶
HasChildResource returns true if the argument resource is a direct child of the responder.
func (*Resource) HasTrailingSlash ¶
func (rb *Resource) HasTrailingSlash() bool
HasTrailingSlash returns true if the responder's URL ends with a trailing slash. If the responder has a trailing slash in its URL and the request is made to the URL without a trailing slash, the responder redirects it to the URL with a trailing slash and vice versa.
func (*Resource) Host ¶
Host returns the host of the resource if the resource is registered in the tree under the host.
func (*Resource) Implementation ¶
func (rb *Resource) Implementation() Impl
Implementation returns the implementation of the responder. If the responder wasn't created from an Impl or if it has no Impl set, nil is returned.
func (*Resource) ImplementationAt ¶
ImplementationAt returns the implementation of the existing resource at the path. If the resource wasn't created from an Impl or it has no Impl set, nil is returned.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
func (*Resource) IsLenientOnTrailingSlash ¶
func (rb *Resource) IsLenientOnTrailingSlash() bool
IsLenientOnTrailingSlash returns true if the responder was configured to ignore an unmatched trailing slash in the request's URL.
func (*Resource) IsLenientOnUncleanPath ¶
func (rb *Resource) IsLenientOnUncleanPath() bool
IsLenientOnUncleanPath returns true if the responder was configured to ignore unclean paths like "example.com///.//resource1//resource2".
func (*Resource) IsSecure ¶
func (rb *Resource) IsSecure() bool
IsSecure returns true if the responder was configured to respond only if it is used under HTTPS.
func (*Resource) IsStrictOnTrailingSlash ¶
func (rb *Resource) IsStrictOnTrailingSlash() bool
IsStrictOnTrailingSlash returns true if the responder was configured to drop the request when the presence or absence of the trailing slash in the request's URL doesn't match with its own URL. By default, the responder redirects the request on unmatched trailing slash.
func (*Resource) IsSubtreeHandler ¶
func (rb *Resource) IsSubtreeHandler() bool
IsSubtreeHandler returns true if the responder was configured to be a subtree handler.
func (*Resource) Name ¶
func (rb *Resource) Name() string
Name returns the name of the responder given in the template.
func (*Resource) Parent ¶
Parent returns the parent resource of the receiver resource if it was registered under the resource. Otherwise, the method returns nil.
func (*Resource) PathHandlerOf ¶
PathHandlerOf returns the HTTP method handler of the existing resource at the path.If the handler doesn't exist, nil is returned.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The argument method is an HTTP method. An exclamation mark "!" can be used to get the not allowed HTTP method handler. Examples: "GET", "POST" or "!".
func (*Resource) PermanentRedirectCode ¶
func (rb *Resource) PermanentRedirectCode() int
PermanentRedirectCode returns the responder's status code for permanent redirects. The code is used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. It's either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Resource) PermanentRedirectCodeAt ¶
PermanentRedirectCodeAt returns the status code of the existing resource at the path for permanent redirects.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The code is used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. It's either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Resource) RedirectAnyRequestAt ¶
RedirectAnyRequestAt configures the resource at the path to redirect requests to another URL. Requests made to the resource or its subtree will all be redirected. Neither the request passer nor the request handler of the resource will be called. Subtree resources specified in the request's URL are not required to exist. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The RedirectAnyRequestAt method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the resource is configured properly.
Example:
var host = NewDormantHost("http://example.com")
host.RedirectAnyRequestAt(
"/simulation",
"http://example.com/reality",
http.StatusMovedPermanently,
)
func (*Resource) RedirectAnyRequestTo ¶
RedirectAnyRequestTo configures the responder to redirect requests to another URL. Requests made to the responder or its subtree will all be redirected. Neither the request passer nor the request handler of the responder will be called. Subtree resources specified in the request's URL are not required to exist. If the responder doesn't exist, it will be created.
The RedirectAnyRequstTo method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the responder is configured properly.
Example:
var host = NewDormantHost("http://example.com")
host.RedirectAnyRequestTo(
"http://www.example.com",
http.StatusPermanentRedirect,
)
func (*Resource) RedirectHandler ¶
func (rb *Resource) RedirectHandler() RedirectHandler
RedirectHandler returns the redirect handler function of the responder.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the responder has been configured to redirect requests to a new location.
func (*Resource) RedirectHandlerAt ¶
func (rb *Resource) RedirectHandlerAt( pathTmplStr string, ) RedirectHandler
RedirectHandlerAt returns the redirect handler function of the existing resource at the path.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the resource has been configured to redirect requests to a new location.
func (*Resource) RedirectRequestAt ¶
RedirectRequestAt configures the resource at the path to redirect requests to another URL. The request handler of the resource won't be called. If the resource is a subtree handler and there is no resource in its subtree to handle a request, the resource redirects the request to the URL, adding the remaining path segments to it. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The RedirectRequestAt method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the resource is configured properly.
Example:
var root = NewDormantResource("https:///")
root.RedirectRequestAt(
"https:///simulation",
"https:///reality",
http.StatusMovedPermanently,
)
func (*Resource) RedirectRequestTo ¶
RedirectRequestTo configures the responder to redirect requests to another URL. The request handler of the responder won't be called. If the responder is a subtree handler and there is no resource in its subtree to handle a request, the responder redirects the request to the URL, adding the remaining path segments to it. If the responder doesn't exist, it will be created.
The RedirectRequstTo method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the responder is configured properly.
Example:
var root = NewDormantResource("https:///")
root.RedirectRequestTo(
"https:///login",
http.StatusPermanentRedirect,
)
func (*Resource) RedirectsInsecureRequest ¶
func (rb *Resource) RedirectsInsecureRequest() bool
RedirectsInsecureRequest returns true if the responder was configured to redirect insecure requests, instead of responding with a "404 Not Found" status code.
The responder can be configured to redirect insecure requests if it's intended to be used in both HTTP and HTTPS servers.
func (*Resource) RegisterResource ¶
func (rb *Resource) RegisterResource(r *Resource)
RegisterResource registers the argument resource below in the tree of the responder.
If the argument resource has a URL template, its corresponding host and path segments must be compatible with the templates of the host and path segment resources above in the tree. The remaining path segments are used as the prefix path segments of the argument resource below the responder. If there are compatible resources with the remaining path segments below the responder, the argument resource will be registered under them. Otherwise, new resources will be created for the missing path segments.
If the argument resource's template collides with the template of one of its siblings, RegisterResource checks which one has the HTTP method handlers set and passes the other one's child resources to it. If both can handle a request, the method panics. Child resources are also checked recursively.
func (*Resource) RegisterResourceUnder ¶
RegisterResourceUnder registers the argument resource below the responder and the prefix path segments.
If the argument resource has a URL template, its host and path segment templates must be compatible with the corresponding host and path segment resources in the tree and with the argument prefix path segments. If there are existing resources compatible with the prefix path segments, the argument resource will be registered under them, otherwise new resources will be created for the missing segments.
If the prefix path segment resources exist and the argument resource's template collides with the last prefix resource's child resource, RegisterResourceUnder checks which one has the HTTP method handlers set and passes the other one's child resources to it. If both can handle a request, the method panics.
The trailing slash in the prefix path is ignored.
func (*Resource) RegisteredResource ¶
RegisteredResource returns the resource in the tree below the responder if it can be reached with the path template. In the path template, names can be used instead of the complete segment templates.
For example,
/childResourceTemplate/$someName/anotherResourceTemplate/, https:///$childResourceName/$grandChildResourceName
The scheme and trailing slash properties must be compatible with the resource's.
func (*Resource) Resource ¶
Resource uses the path template to find an existing resource or to create a new one below in the tree of the responder and returns it. If the path template contains prefix segments that don't have existing resources, the method also creates new resources for them.
If the resource exists, its scheme and trailing slash properties are compared to the values given in the path template. They must match. If the method creates a new resource, its scheme and trailing slash properties are configured using the values given within the path template.
The names given to the path segment resources must be unique in the path and among their respective siblings.
func (*Resource) ResourceUsingConfig ¶
ResourceUsingConfig uses the path template and config to find an existing resource or to create a new one below in the tree of the responder and returns it. If the path template contains prefix segments that don't have existing resources, the method also creates new resources for them.
If the resource exists, its configuration is compared to the argument config. Also, its scheme and trailing slash properties are compared to the values given in the path template. The configuration, scheme, and trailing slash properties must match. If the method creates a new resource, it's configured using the config and the values given in the path template.
The names of the path segment resources must be unique within the path and among their respective siblings.
func (*Resource) Router ¶
func (rb *Resource) Router() *Router
Router returns the router of the responder.
func (*Resource) ServeHTTP ¶
func (rb *Resource) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the Resource's implementations of the http.Handler interface. It is called when the resource is used directly.
func (*Resource) SetConfiguration ¶
func (rb *Resource) SetConfiguration(config Config)
SetConfiguration sets the config for the responder. If the responder has been configured before, it's reconfigured, but the responder's security and trailing slash properties are not affected if they were set to true. In other words, if the responder has been configured to be secure or to have a trailing slash, these properties can't be changed. If the passed config has Secure and/or RedirectsInsecureRequest and/or TrailingSlash fields set to true, the responder's security and trailing slash properties will be set to true, respectively. Please note that, unlike during construction, if the config's RedirectsInsecureRequest field is set to true, the responder will also be configured to be secure, even if it wasn't before. The secure responders only respond when used over HTTPS.
func (*Resource) SetConfigurationAt ¶
SetConfigurationAt sets the config for the resource at the path. If the resource doesn't exist, it will be created. If the existing resource has been configured before, it's reconfigured, but the resource's security and trailing slash properties are not affected if they were set to true. In other words, if the resource has been configured to be secure or to have a trailing slash, these properties can't be changed. If the passed config has Secure and/or RedirectsInsecureRequest and/or TrailingSlash fields set to true, the resource's security and trailing slash properties will be set to true, respectively. Please note that, unlike during construction, if the config's RedirectsInsecureRequest field is set to true, the resource will also be configured to be secure, even if it wasn't before. The secure resources only respond when used over HTTPS.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template as well as in the config. The config's Secure and TrailingSlash values are ignored when creating a new resource.
func (*Resource) SetConfigurationForSubtree ¶
func (rb *Resource) SetConfigurationForSubtree(config Config)
SetConfigurationForSubtree sets the config for all the resources in the subtree, but the resources' security and trailing slash properties are not affected if they were set to true. If the resources are configured with properties other than security and trailing slash, those resources will be skipped.
func (*Resource) SetHandlerFor ¶
SetHandlerFor sets the handler function as a request handler for the HTTP methods.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method and must be used alone. That is, setting the not allowed HTTP method handler must happen in a separate call. Examples of methods: "GET", "PUT, POST", "SHARE, LOCK" or "!".
func (*Resource) SetImplementation ¶
func (rb *Resource) SetImplementation(impl Impl)
SetImplementation sets the HTTP method handlers from the passed impl. The impl is also kept for future retrieval. All existing handlers are discarded.
func (*Resource) SetImplementationAt ¶
SetImplementationAt sets the HTTP method handlers for a resource at the path from the passed Impl's methods. If the resource doesn't exist, the method creates it. The resource keeps the impl for future retrieval. Old handlers of the existing resource are discarded.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
func (*Resource) SetPathHandlerFor ¶
SetPathHandlerFor sets the HTTP methods' handler function for a resource at the path. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method and must be used alone. That is, setting the not allowed HTTP method handler must happen in a separate call. Examples of methods: "GET", "PUT, POST", "SHARE, LOCK" or "!".
func (*Resource) SetPermanentRedirectCode ¶
func (rb *Resource) SetPermanentRedirectCode(code int)
SetPermanentRedirectCode sets the status code for permanent redirects. It's used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. The code is either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Resource) SetPermanentRedirectCodeAt ¶
SetPermanentRedirectCodeAt sets the status code of the resource at the path for permanent redirects. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The status code is sent when redirecting the request to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. The code is either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Resource) SetRedirectHandler ¶
func (rb *Resource) SetRedirectHandler(handler RedirectHandler)
SetRedirectHandler can be used to set a custom implementation of the redirect handler function.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the responder has been configured to redirect requests to a new location.
func (*Resource) SetRedirectHandlerAt ¶
func (rb *Resource) SetRedirectHandlerAt( pathTmplStr string, handler RedirectHandler, )
SetRedirectHandlerAt can be used to set a custom implementation of the redirect handler for a resource at the path. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the resource has been configured to redirect requests to a new location.
func (*Resource) SetSharedData ¶
func (rb *Resource) SetSharedData(data interface{})
SetSharedData sets the data shared between handlers. It's useful when the responder wasn't created from an implementation.
Shared data can be retrieved using the *Args arguments ResponderSharedData method. If the shared data can be modified, accessing it must be synchronized with a mutex or some other synchronization method.
Example:
type SharedData struct {
*sync.Mutex // Must be initilized.
X SomeType
}
...
func SomeHandler(
w http.ResponseWriter,
r *http.Request,
args *nanomux.Args,
) {
var sharedData = args.ResponderSharedData().(*SharedData)
sharedData.Lock()
defer sharedData.Unlock()
sharedData.X = someValue
...
}
func (*Resource) SetSharedDataAt ¶
func (rb *Resource) SetSharedDataAt( pathTmplStr string, data interface{}, )
SetSharedDataAt sets the shared data for the resource at the path. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
func (*Resource) SetSharedDataForSubtree ¶
func (rb *Resource) SetSharedDataForSubtree(data interface{})
SetSharedDataForSubtree sets the shared data for each resource in the subtree that has no shared data set yet.
func (*Resource) SharedData ¶
func (rb *Resource) SharedData() interface{}
SharedData returns the data set by SetSharedData.
func (*Resource) SharedDataAt ¶
func (rb *Resource) SharedDataAt(pathTmplStr string) interface{}
SharedDataAt returns the shared data of the existing resource at the path. If the shared data wasn't set, nil is returned.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
func (*Resource) Template ¶
func (rb *Resource) Template() *Template
Template returns the parsed template of the responder.
func (*Resource) URL ¶
func (rb *Resource) URL(values HostPathValues) (*url.URL, error)
URL returns the responder's URL with values applied to it.
func (*Resource) WrapHandlerOf ¶
func (rb *Resource) WrapHandlerOf(methods string, mws ...Middleware)
WrapHandlerOf wraps the handlers of the HTTP methods with the middlewares in their passed order. All handlers of the HTTP methods stated in the methods argument must exist.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Resource) WrapPathHandlerOf ¶
func (rb *Resource) WrapPathHandlerOf( methods, pathTmplStr string, mws ...Middleware, )
WrapPathHandlerOf wraps the handlers of the HTTP methods of the existing resource at the path. The handlers are wrapped in the middlewares' passed order. All handlers of the HTTP methods stated in the methods argument must exist.
The scheme and trailing slash property values in the path template must be compatible with the resource's properties.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Resource) WrapRedirectHandler ¶
func (rb *Resource) WrapRedirectHandler( mws ...func(RedirectHandler) RedirectHandler, )
WrapRedirectHandler wraps the redirect handler function with middlewares in their passed order.
The method can be used when the handler's default implementation is sufficient and only the response headers need to be changed, or some other additional functionality is required.
The redirect handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It's also used when responder has been configured to redirect requests to a new location.
func (*Resource) WrapRedirectHandlerAt ¶
func (rb *Resource) WrapRedirectHandlerAt( pathTmplStr string, mws ...func(RedirectHandler) RedirectHandler, )
WrapRedirectHandlerAt wraps the redirect handler of the resource at the path. The redirect handler is wrapped in the middlewares' passed order. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The method can be used when the handler's default implementation is sufficient and only the response headers need to be changed, or some other additional functionality is required.
The redirect handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It's also used when resource has been configured to redirect requests to a new location.
func (*Resource) WrapRequestHandler ¶
func (rb *Resource) WrapRequestHandler(mws ...Middleware)
WrapRequestHandler wraps the responder's request handler with the middlewares in their passed order.
The request handler calls the HTTP method handler of the responder depending on the request's method. Unlike the request passer, the request handler is called only when the responder is the one to handle the request and has at least one HTTP method handler.
func (*Resource) WrapRequestHandlerAt ¶
func (rb *Resource) WrapRequestHandlerAt( pathTmplStr string, mws ...Middleware, )
WrapRequestHandlerAt wraps the request handler of the resource at the path. The request handler is wrapped in the middlewares' passed order. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The request handler calls the HTTP method handler of the resource depending on the request's method. Unlike the request passer, the request handler is called only when the resource is the one to handle the request and has at least one HTTP method handler.
func (*Resource) WrapRequestPasser ¶
func (rb *Resource) WrapRequestPasser(mws ...Middleware)
WrapRequestPasser wraps the request passer of the responder with the middlewares in their passed order.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
func (*Resource) WrapRequestPasserAt ¶
func (rb *Resource) WrapRequestPasserAt( pathTmplStr string, mws ...Middleware, )
WrapRequestPasserAt wraps the request passer of the resource at the path. The request passer is wrapped in the middlewares' passed order. If the resource doesn't exist, it will be created.
The scheme and trailing slash property values in the path template must be compatible with the existing resource's properties. A newly created resource is configured with the values in the path template.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
func (*Resource) WrapSubtreeHandlersOf ¶
func (rb *Resource) WrapSubtreeHandlersOf( methods string, mws ...Middleware, )
WrapSubtreeHandlersOf wraps the HTTP method handlers of the resources in the tree below the responder.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Resource) WrapSubtreeRequestHandlers ¶
func (rb *Resource) WrapSubtreeRequestHandlers( mws ...Middleware, )
WrapSubtreeRequestHandlers wraps the request handlers of the resources in the tree below the responder. Handlers are wrapped in the middlewares' passed order.
The request handler calls the HTTP method handler of the responder depending on the request's method. Unlike the request passer, the request handler is called only when the responder is the one to handle the request and has at least one HTTP method handler.
func (*Resource) WrapSubtreeRequestPassers ¶
func (rb *Resource) WrapSubtreeRequestPassers( mws ...Middleware, )
WrapSubtreeRequestPassers wraps the request passers of the resources in the tree below the responder. The request passers are wrapped in the middlewares' passed order.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is an HTTP request router. It passes the incoming requests to their matching host or resources.
func (*Router) ConfigurationAt ¶
ConfigurationAt returns the configuration of the existing responder at the URL.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
func (*Router) HasAnyHost ¶
HasAnyHost returns true if the router has at least one host.
func (*Router) Host ¶
Host returns the host with the template.
If there is no host with the passed template, the method creates a new one and configures it with the scheme and trailing slash property values given in the template. If the host exists, the method compares its scheme and trailing slash properties with the values in the template and panics if there is a difference.
The trailing slash is used only for path segments when the host is a subtree handler and should respond to the request. It has no effect on the host itself. The template cannot be a wildcard template.
The name given to the host must be unique among the other hosts.
func (*Router) HostNamed ¶
HostNamed returns the registered host with the name. If the host doesn't exit, the method returns nil.
func (*Router) HostUsingConfig ¶
HostUsingConfig uses the template and config to find an existing host or to create a new one.
If the host exists, its configuration is compared to the passed config. Also, its scheme and trailing slash properties are compared to the values given in the template. If there is a difference, the method panics. If the method creates a new host, it's configured using the config and the values given in the template.
The trailing slash is used only for path segments when the host is a subtree handler and should respond to the request. It has no effect on the host itself. The template cannot be a wildcard template.
The name given to the host must be unique among the other hosts.
func (*Router) ImplementationAt ¶
ImplementationAt returns the implementation of the existing responder at the URL. If the responder wasn't created from an Impl or it has no Impl set, nil is returned.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
func (*Router) PermanentRedirectCodeAt ¶
PermanentRedirectCodeAt returns the status code of the existing responder at the URL for permanent redirects.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
The code is used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. It's either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Router) RedirectAnyRequestAt ¶
RedirectAnyRequestAt configures the responder at the path to redirect requests to another URL. Requests made to the responder or its subtree will all be redirected. Neither the request passer nor the request handler of the responder will be called. Subtree resources specified in the request's URL are not required to exist. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The RedirectAnyRequestAt method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the responder is configured properly.
Example:
var router = NewRouter() router.RedirectAnyRequestAt( "http://example.com/simulation", "http://example.com/reality", http.StatusMovedPermanently, )
func (*Router) RedirectHandlerAt ¶
func (ro *Router) RedirectHandlerAt(urlTmplStr string) RedirectHandler
RedirectHandlerAt returns the redirect handler function of the existing responder at the URL.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the resource has been configured to redirect requests to a new location.
func (*Router) RedirectRequestAt ¶
RedirectRequestAt configures the responder at the path to redirect requests to another URL. The request handler of the responder won't be called. If the responder is a subtree handler and there is no resource in its subtree to handle a request, the responder redirects the request to the URL, adding the remaining path segments to it. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The RedirectAnyRequestAt method must not be used for redirects from HTTP to HTTPS or from a URL with no trailing slash to a URL with a trailing slash or vice versa. Those redirects are handled automatically by the NanoMux when the responder is configured properly.
Example:
var router = NewRouter() router.RedirectAnyRequestAt( "https:///simulation", "https:///reality", http.StatusMovedPermanently, )
func (*Router) RegisterHost ¶
RegisterHost registers the passed host if its name and template content are unique among the other hosts.
If the host's template collides with the template of any other host, RegisterHost checks which one has HTTP method handlers set and passes the other host's child resources to it. If both hosts can handle a request, the method panics.
func (*Router) RegisterResource ¶
RegisterResource registers the resource under the root resource if it doesn't have a URL template, otherwise it registers the resource under the URL.
When the resource has a URL template and the host or prefix resources coming before it don't exist, the method creates them too.
The content of the resource's template must be unique among its siblings. If the resource has a name, it also must be unique among its siblings as well as in the path.
When there is a resource with the same template among the siblings, both resources are checked. The one that can handle a request and its child resources are kept. Child resources of the other resource that cannot handle a request are passed to the resource that can. Child resources are also checked recursively.
func (*Router) RegisterResourceUnder ¶
RegisterResourceUnder registers the resource under the URL template. If the resource also has a URL template, it is checked for compatibility with the argument URL template.
When the URL template has a host or prefix resources that don't exist, coming before the argument resource, the method creates them too.
The resource's template must be unique among its siblings. If the resource has a name, it also must be unique among its siblings as well as in the path.
When there is a resource with the same template among the siblings, both resources are checked. The one that can handle a request and its child resources are kept. Child resources of the other resource that cannot handle a request are passed to the resource that can. Child resources are also checked recursively.
func (*Router) RegisteredHost ¶
RegisteredHost returns an already registered host. The host template may contain only a name.
For example:
https://$hostName, http://example.com
Template's scheme and trailing slash property values must be compatible with the host's properties, otherwise the method panics.
func (*Router) RegisteredResource ¶
RegisteredResource returns an existing resource with the URL template. If the resource doesn't exist, the method returns nil.
Names can be used in the URL template instead of the entire host or path segment templates.
For example,
https:///$someName/pathSegmentTemplate/$anotherName, http://example.com/pathSegmentTemplate/$someName/$anotherName/ https://$hostName/$resourceName/
The scheme and trailing slash property values in the URL template must be compatible with the resource's properties, otherwise the method panics.
func (*Router) Resource ¶
Resource returns an existing or newly created resource.
When the URL template contains a host template, its path template cannot be empty or root "/" (the Host type itself is responsible for the root path). If the new resource's host or prefix path segment resources don't exist, the method creates them too.
If the resource exists, the URL template's scheme and trailing slash property values must be compatible with the resource's properties, otherwise the method panics. The new resource's scheme and trailing slash properties are configured with the values given in the URL template. The root resource's trailing slash property is ignored.
If the URL template contains path segment names, they must be unique in the path and among their respective siblings. The host's name must be unique among the other hosts.
func (*Router) ResourceUsingConfig ¶
ResourceUsingConfig returns an existing or newly created resource.
When the URL template contains a host template, its path template cannot be empty or root "/" (the Host type itself is responsible for the root path). If the new resource's host or prefix path segment resources don't exist, the method creates them too.
If the resource exists, the URL template's scheme and trailing slash property values, as well as config, must be compatible with the resource's, otherwise the method panics. The new resource is configured with the values given in the URL template and config. The root resource's trailing slash related properties are ignored.
If the URL template contains path segment names, they must be unique in the path and among their respective siblings. The host's name must be unique among the other hosts.
When the config's value RedirectInsecureRequest is true, the URL template must also state that the resource is secure by using HTTPS.
func (*Router) ServeHTTP ¶
func (ro *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the Router's implementation of the http.Handler interface.
func (*Router) SetConfigurationAt ¶
SetConfigurationAt sets the config for the responder at the URL. If the responder doesn't exist, it will be created. If the existing responder has been configured before, it's reconfigured, but the responder's security and trailing slash properties are not affected if they were set to true. In other words, if the responder has been configured to be secure or to have a trailing slash, these properties can't be changed. If the passed config has Secure and/or RedirectsInsecureRequest and/or TrailingSlash fields set to true, the responder's security and trailing slash properties will be set to true, respectively. Please note that, unlike during construction, if the config's RedirectsInsecureRequest field is set to true, the responder will also be configured to be secure, even if it wasn't before. The secure responders only respond when used over HTTPS.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the path template as well as in the config. The config's Secure and TrailingSlash values are ignored when creating a new responder.
func (*Router) SetConfigurationForAll ¶
SetConfigurationForAll sets the config for all the hosts and resources, but the hosts' and resources' secure and trailing slash properties are not affected if they were set to true. If the responders are configured with properties other than security and trailing slash, those responders will be skipped.
func (*Router) SetImplementationAt ¶
SetImplementationAt sets the HTTP method handlers for a responder at the URL from the passed Impl's methods. If the responder doesn't exist, the method creates it. The responder keeps the impl for future retrieval. Old handlers of the existing responder are discarded.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
func (*Router) SetPermanentRedirectCodeAt ¶
SetPermanentRedirectCodeAt sets the status code of the responder at the URL for permanent redirects. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The status code is sent when redirecting the request to an HTTPS from an HTTP, to a URL with a trailing slash from one without, or vice versa. The code is either 301 (moved permanently) or 308 (permanent redirect). The difference between the 301 and 308 status codes is that with the 301 status code, the request's HTTP method may change. For example, some clients change the POST HTTP method to GET. The 308 status code does not allow this behavior. By default, the 308 status code is sent.
func (*Router) SetRedirectHandlerAt ¶
func (ro *Router) SetRedirectHandlerAt( urlTmplStr string, handler RedirectHandler, )
SetRedirectHandlerAt can be used to set a custom implementation of the redirect handler for a responder at the URL. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It is also used when the resource has been configured to redirect requests to a new location.
func (*Router) SetSharedDataAt ¶
SetSharedDataAt sets the shared data for the responder at the URL. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
func (*Router) SetSharedDataForAll ¶
func (ro *Router) SetSharedDataForAll(data interface{})
SetSharedDataForAll sets the shared data for each host and resource that has no shared data set yet.
func (*Router) SetURLHandlerFor ¶
SetURLHandlerFor sets the HTTP methods' handler function for a responder at the URL. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method and must be used alone. That is, setting the not allowed HTTP method handler must happen in a separate call. Examples of methods: "GET", "PUT, POST", "SHARE, LOCK" or "!".
func (*Router) SharedDataAt ¶
SharedDataAt returns the shared data of the existing responder at the URL. If the shared data wasn't set, nil is returned.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
func (*Router) URLHandlerOf ¶
URLHandlerOf returns the HTTP method handler of the existing responder at the URL.If the handler doesn't exist, nil is returned.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
The argument method is an HTTP method. An exclamation mark "!" can be used to get the not allowed HTTP method handler. Examples: "GET", "POST" or "!".
func (*Router) WrapAllHandlersOf ¶
func (ro *Router) WrapAllHandlersOf( methods string, mws ...Middleware, )
WrapAllHandlersOf wraps the handlers of the HTTP methods of all the hosts and resources. Handlers are wrapped in the middlewares' passed order.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
func (*Router) WrapAllRequestHandlers ¶
func (ro *Router) WrapAllRequestHandlers(mws ...Middleware)
WrapAllRequestHandlers wraps all the request handlers of all the hosts and resources. Handlers are wrapped in the middlewares' passed order.
The request handler calls the HTTP method handler of the responder depending on the request's method. Unlike the request passer, the request handler is called only when the responder is the one to handle the request and has at least one HTTP method handler.
func (*Router) WrapAllRequestPassers ¶
func (ro *Router) WrapAllRequestPassers(mws ...Middleware)
WrapAllRequestPassers wraps all the request passers of all the hosts and resources. The request passers are wrapped in the middlewares' passed order.
The request passer is responsible for finding the next resource that matches the next path segment and passing the request to it. If there is no matching resource to the next path segment of the request's URL, the handler for a not-found resource is called.
func (*Router) WrapRedirectHandlerAt ¶
func (ro *Router) WrapRedirectHandlerAt( urlTmplStr string, mws ...func(RedirectHandler) RedirectHandler, )
WrapRedirectHandlerAt wraps the redirect handler of the responder at the URL. The redirect handler is wrapped in the middlewares' passed order. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The method can be used when the handler's default implementation is sufficient and only the response headers need to be changed, or some other additional functionality is required.
The redirect handler is mostly used to redirect requests to an HTTPS from an HTTP, to a URL with a trailing slash from a URL without, or vice versa. It's also used when resource has been configured to redirect requests to a new location.
func (*Router) WrapRequestHandlerAt ¶
func (ro *Router) WrapRequestHandlerAt(urlTmplStr string, mws ...Middleware)
WrapRequestHandlerAt wraps the request handler of the responder at the URL. The request handler is wrapped in the middlewares' passed order. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The request handler calls the HTTP method handler of the responder depending on the request's method. Unlike the request passer, the request handler is called only when the responder is the one to handle the request and has at least one HTTP method handler.
func (*Router) WrapRequestPasser ¶
func (ro *Router) WrapRequestPasser(mws ...Middleware)
WrapRequestPasser wraps the router's request passer with the middlewares in their passed order. The router's request passer is responsible for passing the request to the matching host or the root resource.
func (*Router) WrapRequestPasserAt ¶
func (ro *Router) WrapRequestPasserAt(urlTmplStr string, mws ...Middleware)
WrapRequestPasserAt wraps the request passer of the responder at the URL. The request passer is wrapped in the middlewares' passed order. If the responder doesn't exist, it will be created.
The scheme and trailing slash property values in the URL template must be compatible with the existing responder's properties. A newly created responder is configured with the values in the URL template.
The request passer is responsible for finding the next responder that matches the next path segment and passing the request to it. If there is no matching responder to the next path segment of the request's URL, the handler for a not-found resource is called.
func (*Router) WrapURLHandlerOf ¶
func (ro *Router) WrapURLHandlerOf( methods string, urlTmplStr string, mws ...Middleware, )
WrapURLHandlerOf wraps the handlers of the HTTP methods of the existing responder at the URL. The handlers are wrapped in the middlewares' passed order. All handlers of the HTTP methods stated in the methods argument must exist.
The scheme and trailing slash property values in the URL template must be compatible with the responder's properties.
The argument methods is a list of HTTP methods separated by a comma and/or space. An exclamation mark "!" denotes the handler of the not allowed HTTP method, and an asterisk "*" denotes all the handlers of HTTP methods in use. Both must be used alone. That is, wrapping the not allowed HTTP method handler and all the handlers of HTTP methods in use must happen in separate calls. Examples of methods: "GET", "PUT POST", "SHARE, LOCK", "*" or "!".
type Similarity ¶
type Similarity uint8
Similarity is a degree of difference between templates. :)
const ( // Different templates have different segments. Different Similarity = iota // DifferentValueNames means templates have the same static and/or dynamic // segments but with different value names. DifferentValueNames // DifferentNames means that the templates are identical except for their // names. DifferentNames // TheSame templates have no differences. TheSame )
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template represents the parsed template of the hosts and resources.
A template may have three kinds of segments: static, regexp, and wildcard. The regexp segment must be between curly braces and its value name and pattern separated by ":". The wildcard segment can only have a value name. There can be only one wildcard segment in the template. The regexp and wildcard segments are the dynamic segments of the template. Dynamic segments' names are used as their value names.
A template may have a name. The name comes at the beginning of the template, after the "$" sign and followed by ":". If there is a single dynamic segment in the template and the template doesn't have a name, the dynamic segment's name is used as the name of the template.
If the regexp dynamic segment is repeated in the template, from the second repetition, its pattern may be omitted. When the regexp matches a string, its repetitions must get the same value, otherwise the match fails.
The colon ":" in the template name and in the value name, as well as the curly braces "{" and "}" in the static segments, can be escaped with the backslash "\". The escaped colon ":" is included in the name, and the escaped curly braces "{" and "}" are included in the static segment. If the static segment at the beginning of the template must start with the "$" sign, and the template doesn't need a name, the "$" sign must be escaped too.
Some examples of the template forms:
$templateName:staticPart{valueName:pattern},
$templateName:{valueName:pattern}staticpart,
$templateName:{wildcardName}{valueName1:pattern1}{valueName2:pattern2},
staticTemplate,
{valueName:pattern},
{wildcardSegmentName},
{valueName:pattern}staticPart{wildcardName}{valueName},
$templateName:staticPart1{wildCardName}staticPart2{valueName:pattern}
$templateName:staticPart,
$templateName:{valueName:pattern},
$templateName\:1:{wildCard{Name}}staticPart{value{Name}:pattern},
{valueName\:1:pattern}static\{Part\},
\$staticPart:1{wildcardName}staticPart:2
func Parse ¶
Parse parses the template string and returns the Template instance if it succeeds. Unlike TryToParse, Parse panics on an error.
func TryToParse ¶
TryToParse tries to parse the passed template string, and if successful, returns the Template instance.
func (*Template) Apply ¶
func (t *Template) Apply(values TemplateValues, ignoreMissing bool) string
Apply puts the values in the place of the wildcard segment and regular expression segments if they match, otherwise panics. When ignoreMissing is true, Apply ignores the missing values.
func (*Template) Clear ¶
func (t *Template) Clear()
Clear clears the content and the name of the template.
func (*Template) Content ¶
Content returns the escaped content of the template without a name. The pattern is omitted from repeated regexp segments starting from the second repetition.
func (*Template) HasPattern ¶
HasPattern returns true if the template has any regular expression segments.
func (*Template) HasValueName ¶
HasValueName returns true if one of the dynamic segments of the template has one of the names.
func (*Template) IsStatic ¶
IsStatic returns true if the template doesn't have any dynamic segments.
func (*Template) IsWildcard ¶
IsWildcard returns true if the template doesn't have any static or regular expression segments.
func (*Template) Match ¶
func (t *Template) Match( str string, values TemplateValues, ) (bool, TemplateValues)
Match returns true if the string matches the template. If the template has wildcard or regular expression segments, the method adds the slices of the argument string that match those segments to the values argument and returns it. The names of the wildcard and regular expression segments in the template are used as keys for the values. The values argument is returned as is when the template doesn't match.
func (*Template) SetName ¶
SetName sets the name of the template. The name becomes the name of the host or resource.
func (*Template) SimilarityWith ¶
func (t *Template) SimilarityWith(t2 *Template) Similarity
SimilarityWith returns the similarity between the receiver and argument templates.
func (*Template) String ¶
String returns the template's string. The pattern is omitted from repeated regexp segments starting from the second repetition.
func (*Template) TryToApply ¶
func (t *Template) TryToApply( values TemplateValues, ignoreMissing bool, ) (string, error)
TryToApply puts the values in the place of the wildcard segment and regular expression segments if they match, otherwise returns an error. When ignoreMissing is true, the method ignores the missing values.
func (*Template) UnescapedContent ¶
UnescapedContent returns the unescaped content of the template without a name. The pattern is omitted from repeated regexp segments starting from the second repetition.
func (*Template) ValueNames ¶
ValueNames returns the value names given in the wildcard and regular expression segments.
type TemplateValues ¶
type TemplateValues []_StringPair
TemplateValues is a slice of string key-value pairs.
func (TemplateValues) Get ¶
func (tmplVs TemplateValues) Get(key string) string
Get returns the value of the key. If the key doesn't exist, it returns an empty string.
func (*TemplateValues) Set ¶
func (tmplVs *TemplateValues) Set(key, value string)
Set sets the value for the key. If the key doesn't exist, it's added to the slice.