Documentation
¶
Overview ¶
Package rux is a simple and fast request router for golang HTTP applications.
Source code and other details for the project are available at GitHub:
https://github.com/definitegen/rux
Usage please ref examples and README
Example ¶
r := New()
r.GET("/", func(c *Context) {
c.Text(200, "hello")
})
r.GET("/users/{id}", func(c *Context) {
c.Text(200, "hello")
})
r.POST("/post", func(c *Context) {
c.Text(200, "hello")
})
route, _, _ := r.Match("GET", "/")
fmt.Println(route.Path())
route, params, _ := r.Match("GET", "/users/23")
fmt.Println(route.Path(), params)
// run http server
// r.Listen(":8080")
Output: / /users/{id} map[id:23]
Index ¶
- Constants
- Variables
- func AllMethods() []string
- func AnyMethods() []string
- func CachingWithNum(num uint16) func(*Router)
- func Debug(val bool)
- func EnableCaching(r *Router)
- func GetGlobalVars() map[string]string
- func HandleFallbackRoute(r *Router)
- func HandleMethodNotAllowed(r *Router)
- func InterceptAll(path string) func(*Router)
- func IsDebug() bool
- func MaxNumCaches(num uint16) func(*Router)
- func MethodsString() string
- func NewCachedRoutes(size int) *cachedRoutes
- func SetGlobalVar(name, regex string)
- func StrictLastSlash(r *Router)
- func UseEncodedPath(r *Router)
- type BuildRequestURL
- func (b *BuildRequestURL) Build(withParams ...M) *url.URL
- func (b *BuildRequestURL) Host(host string) *BuildRequestURL
- func (b *BuildRequestURL) Params(params M) *BuildRequestURL
- func (b *BuildRequestURL) Path(path string) *BuildRequestURL
- func (b *BuildRequestURL) Queries(queries url.Values) *BuildRequestURL
- func (b *BuildRequestURL) Scheme(scheme string) *BuildRequestURL
- func (b *BuildRequestURL) User(username, password string) *BuildRequestURL
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortThen() *Context
- func (c *Context) AbortWithStatus(code int, msg ...string)
- func (c *Context) AcceptedTypes() []string
- func (c *Context) AddError(err error)
- func (c *Context) Attachment(srcFile, outName string)
- func (c *Context) AutoBind(obj any) error
- func (c *Context) Back(optionalCode ...int)
- func (c *Context) Binary(status int, in io.ReadSeeker, outName string, inline bool)
- func (c *Context) Bind(obj any) error
- func (c *Context) BindForm(obj any) error
- func (c *Context) BindJSON(obj any) error
- func (c *Context) BindXML(obj any) error
- func (c *Context) Blob(status int, contentType string, data []byte)
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Cookie(name string) string
- func (c *Context) Copy() *Context
- func (c *Context) Data() map[string]any
- func (c *Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) DelCookie(names ...string)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) FastSetCookie(name, value string, maxAge int)
- func (c *Context) File(filePath string)
- func (c *Context) FileContent(file string, names ...string)
- func (c *Context) FirstError() error
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormParams(excepts ...[]string) (url.Values, error)
- func (c *Context) Get(key string) (v any, ok bool)
- func (c *Context) HTML(status int, data []byte)
- func (c *Context) HTMLString(status int, data string)
- func (c *Context) HTTPError(msg string, status int)
- func (c *Context) Handler() HandlerFunc
- func (c *Context) HandlerName() string
- func (c *Context) Header(key string) string
- func (c *Context) Init(w http.ResponseWriter, r *http.Request)
- func (c *Context) Inline(srcFile, outName string)
- func (c *Context) IsAborted() bool
- func (c *Context) IsAjax() bool
- func (c *Context) IsGet() bool
- func (c *Context) IsMethod(method string) bool
- func (c *Context) IsPost() bool
- func (c *Context) IsTLS() bool
- func (c *Context) IsWebSocket() bool
- func (c *Context) JSON(status int, obj any)
- func (c *Context) JSONBytes(status int, bs []byte)
- func (c *Context) JSONP(status int, callback string, obj any)
- func (c *Context) Length() int
- func (c *Context) MustBind(obj any, binder binding.Binder)
- func (c *Context) MustRender(status int, obj any, renderer render.Renderer)
- func (c *Context) Next()
- func (c *Context) NoContent()
- func (c *Context) Param(key string) string
- func (c *Context) ParseMultipartForm(maxMemory ...int) error
- func (c *Context) Post(key string, defVal ...string) string
- func (c *Context) PostParam(key string) (string, bool)
- func (c *Context) PostParams(key string) ([]string, bool)
- func (c *Context) Query(key string, defVal ...string) string
- func (c *Context) QueryParam(key string) (string, bool)
- func (c *Context) QueryParams(key string) ([]string, bool)
- func (c *Context) QueryValues() url.Values
- func (c *Context) RawBodyData() ([]byte, error)
- func (c *Context) RawWriter() http.ResponseWriter
- func (c *Context) Redirect(path string, optionalCode ...int)
- func (c *Context) Render(status int, name string, data any) (err error)
- func (c *Context) ReqCtxValue(key any) any
- func (c *Context) Reset()
- func (c *Context) Respond(status int, obj any, renderer render.Renderer)
- func (c *Context) Router() *Router
- func (c *Context) SafeGet(key string) any
- func (c *Context) SaveFile(file *multipart.FileHeader, dst string) error
- func (c *Context) Set(key string, val any)
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) SetHandlers(handlers HandlersChain)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) SetStatus(status int)
- func (c *Context) SetStatusCode(status int)
- func (c *Context) ShouldBind(obj any, binder binding.Binder) error
- func (c *Context) ShouldRender(status int, obj any, renderer render.Renderer) error
- func (c *Context) StatusCode() int
- func (c *Context) Stream(status int, contentType string, r io.Reader)
- func (c *Context) Text(status int, str string)
- func (c *Context) URL() *url.URL
- func (c *Context) UploadFile(name string, saveAs string) error
- func (c *Context) Validate(obj any) error
- func (c *Context) Value(key any) any
- func (c *Context) WithReqCtxValue(key, val any)
- func (c *Context) WriteBytes(bt []byte)
- func (c *Context) WriteString(str string)
- func (c *Context) XML(status int, obj any, indents ...string)
- type ControllerFace
- type HandlerFunc
- type HandlersChain
- type M
- type Params
- type Renderer
- type Route
- func (r *Route) AttachTo(router *Router)
- func (r *Route) Handler() HandlerFunc
- func (r *Route) HandlerName() string
- func (r *Route) Handlers() HandlersChain
- func (r *Route) Info() RouteInfo
- func (r *Route) MethodString(char string) string
- func (r *Route) Methods() []string
- func (r *Route) Name() string
- func (r *Route) NamedTo(name string, router *Router)
- func (r *Route) Path() string
- func (r *Route) String() string
- func (r *Route) ToURL(buildArgs ...any) *url.URL
- func (r *Route) Use(middleware ...HandlerFunc) *Route
- type RouteInfo
- type Router
- func (r *Router) Add(path string, handler HandlerFunc, methods ...string) *Route
- func (r *Router) AddNamed(name, path string, handler HandlerFunc, methods ...string) *Route
- func (r *Router) AddRoute(route *Route) *Route
- func (r *Router) Any(path string, handler HandlerFunc, middles ...HandlerFunc)
- func (r *Router) BuildRequestURL(name string, buildArgs ...any) *url.URL
- func (r *Router) BuildURL(name string, buildArgs ...any) *url.URL
- func (r *Router) CONNECT(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) Controller(basePath string, controller ControllerFace, middles ...HandlerFunc)
- func (r *Router) DELETE(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) Err() error
- func (r *Router) GET(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) GetRoute(name string) *Route
- func (r *Router) Group(prefix string, register func(), middles ...HandlerFunc)
- func (r *Router) HEAD(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) HandleContext(c *Context)
- func (r *Router) Handlers() HandlersChain
- func (r *Router) IterateRoutes(fn func(route *Route))
- func (r *Router) Listen(addr ...string)
- func (r *Router) ListenTLS(addr, certFile, keyFile string)
- func (r *Router) ListenUnix(file string)
- func (r *Router) Match(method, path string) (route *Route, ps Params, alm []string)
- func (r *Router) NamedRoutes() map[string]*Route
- func (r *Router) NotAllowed(handlers ...HandlerFunc)
- func (r *Router) NotFound(handlers ...HandlerFunc)
- func (r *Router) OPTIONS(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) PATCH(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) POST(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) PUT(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) QuickMatch(method, path string) (route *Route, ps Params, alm []string)
- func (r *Router) Resource(basePath string, controller any, middles ...HandlerFunc)
- func (r *Router) Routes() (rs []RouteInfo)
- func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)
- func (r *Router) StaticDir(prefixURL string, fileDir string)
- func (r *Router) StaticFS(prefixURL string, fs http.FileSystem)
- func (r *Router) StaticFile(path, filePath string)
- func (r *Router) StaticFiles(prefixURL string, rootDir string, exts string)
- func (r *Router) StaticFunc(path string, handler func(c *Context))
- func (r *Router) String() string
- func (r *Router) TRACE(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
- func (r *Router) Use(middles ...HandlerFunc)
- func (r *Router) WithOptions(options ...func(*Router))
- func (r *Router) WrapHTTPHandlers(preHandlers ...func(h http.Handler) http.Handler) http.Handler
- type Validator
Examples ¶
Constants ¶
const ( GET = "GET" PUT = "PUT" HEAD = "HEAD" POST = "POST" PATCH = "PATCH" TRACE = "TRACE" DELETE = "DELETE" CONNECT = "CONNECT" OPTIONS = "OPTIONS" )
All supported HTTP verb methods name
const ( // ContentType header key ContentType = "Content-Type" // ContentBinary represents content type application/octet-stream ContentBinary = "application/octet-stream" // ContentDisposition describes contentDisposition ContentDisposition = "Content-Disposition" )
const ( // CTXRecoverResult key name in the context CTXRecoverResult = "_recoverResult" // CTXAllowedMethods key name in the context CTXAllowedMethods = "_allowedMethods" // CTXCurrentRouteName key name in the context CTXCurrentRouteName = "_currentRouteName" // CTXCurrentRoutePath key name in the context CTXCurrentRoutePath = "_currentRoutePath" )
Variables ¶
var ( IndexAction = "Index" CreateAction = "Create" StoreAction = "Store" ShowAction = "Show" EditAction = "Edit" UpdateAction = "Update" DeleteAction = "Delete" // RESTFulActions action methods definition RESTFulActions = map[string][]string{ IndexAction: {GET}, CreateAction: {GET}, StoreAction: {POST}, ShowAction: {GET}, EditAction: {GET}, UpdateAction: {PUT, PATCH}, DeleteAction: {DELETE}, } )
RESTFul method names definition
Functions ¶
func HandleFallbackRoute ¶
func HandleFallbackRoute(r *Router)
HandleFallbackRoute enable for the router
func HandleMethodNotAllowed ¶
func HandleMethodNotAllowed(r *Router)
HandleMethodNotAllowed enable for the router
func InterceptAll ¶
InterceptAll setting for the router
func NewCachedRoutes ¶
func NewCachedRoutes(size int) *cachedRoutes
NewCachedRoutes Get Cache pointer
Types ¶
type BuildRequestURL ¶
type BuildRequestURL struct {
// contains filtered or unexported fields
}
BuildRequestURL struct
func (*BuildRequestURL) Host ¶
func (b *BuildRequestURL) Host(host string) *BuildRequestURL
Host set Host
func (*BuildRequestURL) Params ¶
func (b *BuildRequestURL) Params(params M) *BuildRequestURL
Params set Params
func (*BuildRequestURL) Path ¶
func (b *BuildRequestURL) Path(path string) *BuildRequestURL
Path set Path
func (*BuildRequestURL) Queries ¶
func (b *BuildRequestURL) Queries(queries url.Values) *BuildRequestURL
Queries set Queries
func (*BuildRequestURL) Scheme ¶
func (b *BuildRequestURL) Scheme(scheme string) *BuildRequestURL
Scheme set Scheme
func (*BuildRequestURL) User ¶
func (b *BuildRequestURL) User(username, password string) *BuildRequestURL
User set User
type Context ¶
type Context struct {
Req *http.Request
Resp http.ResponseWriter
// current route Params, if route has var Params
Params Params
Errors []error
// contains filtered or unexported fields
}
Context for http server
func (*Context) Abort ¶
func (c *Context) Abort()
Abort will abort at the end of this middleware run
func (*Context) AbortThen ¶
AbortThen will abort at the end of this middleware run, and return context to continue.
func (*Context) AbortWithStatus ¶
AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
func (*Context) AcceptedTypes ¶
AcceptedTypes get Accepted Types.
func (*Context) Attachment ¶
Attachment a file to response.
Usage:
c.Attachment("path/to/some.zip", "new-name.zip")
func (*Context) AutoBind ¶
AutoBind auto bind request data to a struct, will auto select binding.Binder by content-type
Usage:
err := c.AutoBind(&user)
func (*Context) Binary ¶
Binary serve data as Binary response.
Usage:
in, _ := os.Open("./README.md")
r.Binary(http.StatusOK, in, "readme.md", true)
func (*Context) Bind ¶
Bind auto bind request data to a struct, will auto select binding.Binder by content-type. Alias method of the AutoBind()
Usage:
err := c.Bind(&user)
func (*Context) BindForm ¶
BindForm request data to an struct, will auto call validator
Usage:
err := c.BindForm(&user)
func (*Context) BindJSON ¶
BindJSON request data to an struct, will auto call validator
Usage:
err := c.BindJSON(&user)
func (*Context) BindXML ¶
BindXML request data to an struct, will auto call validator
Usage:
err := c.BindXML(&user)
func (*Context) Cookie ¶
Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.
func (*Context) Deadline ¶
Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.
func (*Context) Done ¶
func (c *Context) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value.
func (*Context) Err ¶
Err returns a non-nil error value after Done is closed, successive calls to Err return the same error. If Done is not yet closed, Err returns nil. If Done is closed, Err returns a non-nil error explaining why: Canceled if the context was canceled or DeadlineExceeded if the context's deadline passed.
func (*Context) FastSetCookie ¶
FastSetCookie Quick Set Cookie
func (*Context) FileContent ¶
FileContent serves given file as text content to response.
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the first file for the provided form key.
func (*Context) FormParams ¶
FormParams return body values
func (*Context) HTMLString ¶
HTMLString writes out as html text. if data is empty, only write headers
func (*Context) HandlerName ¶
HandlerName get the main handler name
func (*Context) Init ¶
func (c *Context) Init(w http.ResponseWriter, r *http.Request)
Init a context
func (*Context) IsWebSocket ¶
IsWebSocket returns true if the request headers indicate that a webSocket handshake is being initiated by the client.
func (*Context) MustBind ¶
MustBind bind request data to a struct, will auto call validator
Usage:
c.MustBind(&user, binding.Json)
func (*Context) MustRender ¶
MustRender render and response to client
func (*Context) NoContent ¶
func (c *Context) NoContent()
NoContent serve success but no content response
func (*Context) Param ¶
Param returns the value of the URL param.
router.GET("/user/{id}", func(c *rux.Context) {
// a GET request to /user/john
id := c.Param("id") // id == "john"
})
func (*Context) ParseMultipartForm ¶
ParseMultipartForm parse multipart forms.
Tips:
c.Req.PostForm = POST(PUT,PATCH) body data c.Req.Form = c.Req.PostForm + GET queries data c.Req.MultipartForm = uploaded files data + other body fields data(will append to Req.Form and Req.PostForm)
func (*Context) PostParams ¶
PostParams return body values by key
func (*Context) QueryParam ¶
QueryParam return query value by key
func (*Context) QueryParams ¶
QueryParams return query values by key
func (*Context) QueryValues ¶
QueryValues get URL query data
func (*Context) RawBodyData ¶
RawBodyData get raw body data
func (*Context) RawWriter ¶
func (c *Context) RawWriter() http.ResponseWriter
RawWriter get raw http.ResponseWriter instance
func (*Context) ReqCtxValue ¶
ReqCtxValue get context value from http.Request.ctx
Example:
// record value to Request.ctx
r := c.Req
c.Req = r.WithContext(context.WithValue(r.Context(), "key", "value"))
// ...
val := c.ReqCtxValue("key") // "value"
func (*Context) SaveFile ¶
func (c *Context) SaveFile(file *multipart.FileHeader, dst string) error
SaveFile uploads the form file to specific dst.
func (*Context) Set ¶
Set a value to context by key. Usage:
c.Set("key", "value")
// ...
val := c.Get("key") // "value"
func (*Context) SetCookie ¶
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*Context) SetHandlers ¶
func (c *Context) SetHandlers(handlers HandlersChain)
SetHandlers set handlers
func (*Context) SetStatusCode ¶
SetStatusCode code for the response. alias of the SetStatus()
func (*Context) ShouldBind ¶
ShouldBind bind request data to a struct, will auto call validator
Usage:
err := c.ShouldBind(&user, binding.JSON)
func (*Context) ShouldRender ¶
ShouldRender render and response to client
func (*Context) StatusCode ¶
StatusCode get status code from the response
func (*Context) UploadFile ¶
UploadFile handle upload file and save as local file
func (*Context) Validate ¶
Validate input struct or map data. should call Bind() before validate.
Recommended use ShouldBind() instead, it will binding and validate.
func (*Context) Value ¶
Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.
func (*Context) WithReqCtxValue ¶
WithReqCtxValue with request ctx Value.
Usage:
ctx.WithReqCtxValue()
func (*Context) WriteBytes ¶
WriteBytes write byte data to response, will panic on error.
func (*Context) WriteString ¶
WriteString write string to response
type ControllerFace ¶
type ControllerFace interface {
// AddRoutes for support register routes in the controller.
AddRoutes(g *Router)
}
ControllerFace a simple controller interface
type HandlerFunc ¶
type HandlerFunc func(c *Context)
HandlerFunc a handler definition
func HTTPHandler ¶
func HTTPHandler(gh http.Handler) HandlerFunc
HTTPHandler warp a generic http.Handler as an rux HandlerFunc
func HTTPHandlerFunc ¶
func HTTPHandlerFunc(hf http.HandlerFunc) HandlerFunc
HTTPHandlerFunc warp a generic http.HandlerFunc as a rux HandlerFunc
func WrapH ¶
func WrapH(hh http.Handler) HandlerFunc
WrapH warp an generic http.Handler as an rux HandlerFunc
func WrapHF ¶
func WrapHF(hf http.HandlerFunc) HandlerFunc
WrapHF warp a generic http.HandlerFunc as a rux HandlerFunc
func WrapHTTPHandler ¶
func WrapHTTPHandler(gh http.Handler) HandlerFunc
WrapHTTPHandler warp a generic http.Handler as an rux HandlerFunc
func WrapHTTPHandlerFunc ¶
func WrapHTTPHandlerFunc(hf http.HandlerFunc) HandlerFunc
WrapHTTPHandlerFunc warp a generic http.HandlerFunc as a rux HandlerFunc
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implement the http.Handler
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain middleware handlers chain definition
func (HandlersChain) Last ¶
func (c HandlersChain) Last() HandlerFunc
Last returns the last handler in the chain. ie. the last handler is the main own.
type Route ¶
type Route struct {
// Opts some options data for the route
Opts map[string]any
// contains filtered or unexported fields
}
Route in the router
func NamedRoute ¶
func NamedRoute(name, path string, handler HandlerFunc, methods ...string) *Route
NamedRoute create a new route with name. alias of NewNamedRoute()
func NewNamedRoute ¶
func NewNamedRoute(name, path string, handler HandlerFunc, methods ...string) *Route
NewNamedRoute create a new route with name
func NewRoute ¶
func NewRoute(path string, handler HandlerFunc, methods ...string) *Route
NewRoute create a new route
func (*Route) HandlerName ¶
HandlerName get the main handler name
func (*Route) Handlers ¶
func (r *Route) Handlers() HandlersChain
Handlers returns handlers of the route.
func (*Route) MethodString ¶
MethodString join allowed methods to an string
func (*Route) Use ¶
func (r *Route) Use(middleware ...HandlerFunc) *Route
Use add middleware handlers to the route
type RouteInfo ¶
type RouteInfo struct {
Name, Path, HandlerName string
// supported method of the route
Methods []string
HandlerNum int
}
RouteInfo simple route info struct
type Router ¶
type Router struct {
// router name
Name string
//
// Router Settings:
//
// OnError on happen error
OnError HandlerFunc
// OnPanic on happen panic
OnPanic HandlerFunc
// Renderer template(view) interface
// Deprecated: will be removed
Renderer Renderer
// contains filtered or unexported fields
}
Router definition
func New ¶
New router instance, can with some options.
Quick start:
r := New()
r.GET("/path", MyAction)
With options:
r := New(EnableCaching, MaxNumCaches(1000))
r.GET("/path", MyAction)
func (*Router) Add ¶
func (r *Router) Add(path string, handler HandlerFunc, methods ...string) *Route
Add a route to router, allow set multi method Usage:
r.Add("/path", myHandler)
r.Add("/path1", myHandler, "GET", "POST")
func (*Router) AddNamed ¶
func (r *Router) AddNamed(name, path string, handler HandlerFunc, methods ...string) *Route
AddNamed add an named route to router, allow set multi method
func (*Router) Any ¶
func (r *Router) Any(path string, handler HandlerFunc, middles ...HandlerFunc)
Any add route and allow any request methods
func (*Router) BuildRequestURL ¶
BuildRequestURL alias of the method BuildRequestURL()
func (*Router) CONNECT ¶
func (r *Router) CONNECT(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
CONNECT add routing and only allow CONNECT request methods
func (*Router) Controller ¶
func (r *Router) Controller(basePath string, controller ControllerFace, middles ...HandlerFunc)
Controller register some routes by a controller
func (*Router) DELETE ¶
func (r *Router) DELETE(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
DELETE add routing and only allow OPTIONS request methods
func (*Router) GET ¶
func (r *Router) GET(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
GET add routing and only allow GET request methods
func (*Router) Group ¶
func (r *Router) Group(prefix string, register func(), middles ...HandlerFunc)
Group add an group routes, can with middleware
func (*Router) HEAD ¶
func (r *Router) HEAD(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
HEAD add routing and only allow HEAD request methods
func (*Router) HandleContext ¶
HandleContext handle a given context
func (*Router) IterateRoutes ¶
IterateRoutes iterate all routes
func (*Router) Listen ¶
Listen quick create a HTTP server with the router
Usage:
r.Listen("8090")
r.Listen("IP:PORT")
r.Listen("IP", "PORT")
func (*Router) ListenTLS ¶
ListenTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
func (*Router) ListenUnix ¶
ListenUnix attaches the router to a http.Server and starts listening and serving HTTP requests through the specified unix socket (i.e. a file)
func (*Router) Match ¶
Match route by given request METHOD and URI path
ps - route path Params, when has path vars. alm - allowed request methods
func (*Router) NamedRoutes ¶
NamedRoutes get all named routes.
func (*Router) NotAllowed ¶
func (r *Router) NotAllowed(handlers ...HandlerFunc)
NotAllowed handlers for router
func (*Router) NotFound ¶
func (r *Router) NotFound(handlers ...HandlerFunc)
NotFound handlers for router
func (*Router) OPTIONS ¶
func (r *Router) OPTIONS(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
OPTIONS add routing and only allow OPTIONS request methods
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
PATCH add routing and only allow PATCH request methods
func (*Router) POST ¶
func (r *Router) POST(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
POST add routing and only allow POST request methods
func (*Router) PUT ¶
func (r *Router) PUT(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
PUT add routing and only allow PUT request methods
func (*Router) QuickMatch ¶
QuickMatch match route by given request METHOD and URI path ps - route path Params, when has path vars. alm - allowed request methods
func (*Router) Resource ¶
func (r *Router) Resource(basePath string, controller any, middles ...HandlerFunc)
Resource register RESTFul style routes by a controller
Methods Path Action Route Name
GET /resource index resource_index
GET /resource/create create resource_create
POST /resource store resource_store
GET /resource/{id} show resource_show
GET /resource/{id}/edit edit resource_edit
PUT/PATCH /resource/{id} update resource_update
DELETE /resource/{id} delete resource_delete
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)
ServeHTTP for handle HTTP request, response data to client.
Example ¶
r := New()
r.GET("/", func(c *Context) {
c.Text(200, "hello")
})
r.GET("/users/{id}", func(c *Context) {
c.Text(200, "hello")
})
r.POST("/post", func(c *Context) {
c.Text(200, "hello")
})
r.Listen(":8080")
func (*Router) StaticDir ¶
StaticDir add a static asset file handle
Usage:
r.StaticDir("/assets", "/static")
// access GET /assets/css/site.css -> will find /static/css/site.css
func (*Router) StaticFS ¶
func (r *Router) StaticFS(prefixURL string, fs http.FileSystem)
StaticFS add a file system handle.
func (*Router) StaticFile ¶
StaticFile add a static asset file handle
func (*Router) StaticFiles ¶
StaticFiles static files from the given file system root. and allow limit extensions.
Usage:
router.ServeFiles("/src", "/var/www", "css|js|html")
Notice: if the rootDir is relation path, it is relative the server runtime dir.
func (*Router) StaticFunc ¶
StaticFunc add a static asset file handle
func (*Router) TRACE ¶
func (r *Router) TRACE(path string, handler HandlerFunc, middleware ...HandlerFunc) *Route
TRACE add routing and only allow TRACE request methods
func (*Router) Use ¶
func (r *Router) Use(middles ...HandlerFunc)
Use add handlers/middles for the router or group
func (*Router) WithOptions ¶
WithOptions for the router
func (*Router) WrapHTTPHandlers ¶
WrapHTTPHandlers apply some pre http handlers for the router.
Usage:
import "github.com/definitegen/rux/handlers"
r := rux.New()
// ... add routes
handler := r.WrapHTTPHandlers(handlers.HTTPMethodOverrideHandler)
http.ListenAndServe(":8080", handler)