Rux
Simple and fast web framework for build golang HTTP applications.
- Fast route match, support route group
- Support route path params and named routing
- Support cache recently accessed dynamic routes
- Support route middleware, group middleware, global middleware
- Support quickly add a
RESETFul
or Controller
style structs - Support generic
http.Handler
interface middleware - Support static file access handle
- Support add handlers for handle
NotFound
and NotAllowed
中文说明请看 README.zh-CN
GoDoc
Install
go get github.com/gookit/rux
Quick start
NOTICE: v1.3.x
is not fully compatible with v1.2.x
version
package main
import (
"github.com/gookit/rux"
)
func main() {
r := rux.New()
r.GET("/", func(c *rux.Context) {
c.Text(200, "hello")
})
r.GET("/hello/{name}", func(c *rux.Context) {
c.Text(200, "hello " + c.Param("name"))
})
r.POST("/post", func(c *rux.Context) {
c.Text(200, "hello")
})
r.Add("/post[/{id}]", func(c *rux.Context) {
if c.Param("id") == "" {
c.Text(200, "created")
return
}
id := c.Params.Int("id")
c.Text(200, "updated " + fmt.Sprint(id))
}, rux.POST, rux.PUT)
r.Listen(":8080")
}
Route Group
r.Group("/articles", func() {
r.GET("", func(c *rux.Context) {
c.Text(200, "view list")
})
r.POST("", func(c *rux.Context) {
c.Text(200, "create ok")
})
r.GET(`/{id:\d+}`, func(c *rux.Context) {
c.Text(200, "view detail, id: " + c.Param("id"))
})
})
Path Params
You can add the path params like: {id}
Or {id:\d+}
r.GET(`/blog/{id:\d+}`, func(c *rux.Context) {
c.Text(200, "view detail, id: " + c.Param("id"))
})
optional params, like /about[.html]
or /posts[/{id}]
:
r.GET(`/blog/{title:\w+}[.html]`, func(c *rux.Context) {
c.Text(200, "view detail, id: " + c.Param("id"))
})
r.Add("/posts[/{id}]", func(c *rux.Context) {
if c.Param("id") == "" {
c.Text(200, "created")
return
}
id := c.Params.Int("id")
c.Text(200, "updated " + fmt.Sprint(id))
}, rux.POST, rux.PUT)
Use Middleware
rux support use middleware, allow:
- global middleware
- group middleware
- route middleware
Call priority: global middleware -> group middleware -> route middleware
Examples:
package main
import (
"fmt"
"github.com/gookit/rux"
)
func main() {
r := rux.New()
r.Use(func(c *rux.Context) {
})
route := r.GET("/middle", func(c *rux.Context) {
c.WriteString("-O-")
}, func(c *rux.Context) {
c.WriteString("a")
c.Next()
c.WriteString("A")
})
route.Use(func(c *rux.Context) {
c.WriteString("b")
c.Next()
c.WriteString("B")
})
}
- Call sequence:
middle 1 -> middle 2 -> main handler -> middle 2 -> middle 1
- Flow chart:
+-----------------------------+
| middle 1 |
| +----------------------+ |
| | middle 2 | |
start | | +----------------+ | | end
------->| | | main handler | | |--->----
| | |________________| | |
| |______________________| |
|_____________________________|
more please see middleware_test.go middleware tests
Use http.Handler
rux is support generic http.Handler
interface middleware
You can use rux.WrapHTTPHandler()
convert http.Handler
as rux.HandlerFunc
package main
import (
"net/http"
"github.com/gookit/rux"
"github.com/gorilla/handlers"
)
func main() {
r := rux.New()
h0 := http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
w.Header().Set("new-key", "val")
})
r.Use(rux.WrapHTTPHandler(h0), rux.WrapHTTPHandler(handlers.ProxyHeaders()))
r.GET("/", func(c *rux.Context) {
c.Text(200, "hello")
})
http.ListenAndServe(":8000", handlers.CompressHandler(r))
}
More Usage
Static Assets
package main
import (
"embed"
"net/http"
"github.com/gookit/rux"
)
var embAssets embed.FS
func main() {
r := rux.New()
r.StaticFile("/site.js", "testdata/site.js")
r.StaticDir("/static", "testdata")
r.StaticFiles("/assets", "testdata", "css|js")
r.StaticFS("/embed", http.FS(embAssets))
}
Name Route
In rux
, you can add a named route, and you can get the corresponding route instance(rux.Route
) from the router according to the name.
Examples:
r := rux.New()
myRoute := rux.NewNamedRoute("name1", "/path4/some/{id}", emptyHandler, "GET")
r.AddRoute(myRoute)
rux.AddNamed("name2", "/", func(c *rux.Context) {
c.Text(200, "hello")
})
r.GET("/hi", func(c *rux.Context) {
c.Text(200, "hello")
}).NamedTo("name3", r)
myRoute = r.GetRoute("name1")
Redirect
redirect to other page
r.GET("/", func(c *rux.Context) {
c.AbortThen().Redirect("/login", 302)
})
r.GET("/", func(c *rux.Context) {
c.Redirect("/login", 302)
c.Abort()
})
r.GET("/", func(c *rux.Context) {
c.Back()
c.Abort()
})
Cookies
you can quick operate cookies by FastSetCookie()
DelCookie()
Note: You must set or delete cookies before writing BODY content
r.GET("/setcookie", func(c *rux.Context) {
c.FastSetCookie("rux_cookie2", "test-value2", 3600)
c.SetCookie("rux_cookie", "test-value1", 3600, "/", c.Req.URL.Host, false, true)
c.WriteString("hello, in " + c.URL().Path)
})
r.GET("/delcookie", func(c *rux.Context) {
val := ctx.Cookie("rux_cookie")
c.DelCookie("rux_cookie", "rux_cookie2")
})
Multi Domains
code is refer from julienschmidt/httprouter
package main
import (
"log"
"net/http"
"github.com/gookit/rux"
)
type HostSwitch map[string]http.Handler
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if router := hs[r.Host]; router != nil {
router.ServeHTTP(w, r)
} else {
http.Error(w, "Forbidden", 403)
}
}
func main() {
router := rux.New()
router.GET("/", Index)
router.GET("/hello/{name}", func(c *rux.Context) {})
hs := make(HostSwitch)
hs["example.com:12345"] = router
log.Fatal(http.ListenAndServe(":12345", hs))
}
RESETFul Style
package main
import (
"log"
"net/http"
"github.com/gookit/rux"
)
type Product struct {
}
func (Product) Uses() map[string][]rux.HandlerFunc {
return map[string][]rux.HandlerFunc{
"Delete": []rux.HandlerFunc{
handlers.HTTPBasicAuth(map[string]string{"test": "123"}),
handlers.GenRequestID(),
},
}
}
func (p *Product) Index(c *rux.Context) {
}
func (p *Product) Create(c *rux.Context) {
}
func (p *Product) Store(c *rux.Context) {
}
func (p *Product) Show(c *rux.Context) {
}
func (p *Product) Edit(c *rux.Context) {
}
func (p *Product) Update(c *rux.Context) {
}
func (p *Product) Delete(c *rux.Context) {
}
func main() {
router := rux.New()
router.Resource("/", new(Product))
log.Fatal(http.ListenAndServe(":12345", router))
}
Controller Style
package main
import (
"log"
"net/http"
"github.com/gookit/rux"
)
type News struct {
}
func (n *News) AddRoutes(g *rux.Router) {
g.GET("/", n.Index)
g.POST("/", n.Create)
g.PUT("/", n.Edit)
}
func (n *News) Index(c *rux.Context) {
}
func (n *News) Create(c *rux.Context) {
}
func (n *News) Edit(c *rux.Context) {
}
func main() {
router := rux.New()
router.Controller("/news", new(News))
log.Fatal(http.ListenAndServe(":12345", router))
}
Build URL
package main
import (
"log"
"net/http"
"github.com/gookit/rux"
)
func main() {
router := rux.New()
router.GET(`/news/{category_id}/{new_id:\d+}/detail`, func(c *rux.Context) {
var u = make(url.Values)
u.Add("username", "admin")
u.Add("password", "12345")
b := rux.NewBuildRequestURL()
b.Queries(u)
b.Params(rux.M{"{category_id}": "100", "{new_id}": "20"})
println(c.Router().BuildRequestURL("new_detail", b).String())
if c.MustGet(rux.CTXCurrentRouteName) == "new_detail" {
}
}).NamedTo("new_detail", router)
log.Fatal(http.ListenAndServe(":12345", router))
}
Help
golint ./...
gofmt -s -l ./
gofmt -s -w some.go
go test -cover ./...
Gookit Packages
- gookit/ini Go config management, use INI files
- gookit/rux Simple and fast request router for golang HTTP
- gookit/gcli build CLI application, tool library, running CLI commands
- gookit/slog Concise and extensible go log library
- gookit/event Lightweight event manager and dispatcher implements by Go
- gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
- gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
- gookit/color A command-line color library with true color support, universal API methods and Windows support
- gookit/filter Provide filtering, sanitizing, and conversion of golang data
- gookit/validate Use for data validation and filtering. support Map, Struct, Form data
- gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
- More please see https://github.com/gookit
See also
License
MIT