Skip to content

Commit

Permalink
👔 up: add some new render func, update deps, remove tests on go < 1.18
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 19, 2023
1 parent c9d7bf2 commit 8908e05
Show file tree
Hide file tree
Showing 9 changed files with 95 additions and 55 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
go_version: [1.16, 1.17, 1.18, 1.19]
go_version: ['1.20', 1.18, 1.19]

steps:
- name: Check out code
Expand Down
40 changes: 22 additions & 18 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rux
import (
"context"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
Expand Down Expand Up @@ -120,9 +119,10 @@ func (c *Context) Copy() *Context {

// Set a value to context by key.
// Usage:
// c.Set("key", "value")
// // ...
// val := c.Get("key") // "value"
//
// c.Set("key", "value")
// // ...
// val := c.Get("key") // "value"
func (c *Context) Set(key string, val interface{}) {
if c.data == nil {
c.data = make(map[string]interface{})
Expand Down Expand Up @@ -187,10 +187,11 @@ func (c *Context) FirstError() error {
*************************************************************/

// 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"
// })
//
// router.GET("/user/{id}", func(c *rux.Context) {
// // a GET request to /user/john
// id := c.Param("id") // id == "john"
// })
func (c *Context) Param(key string) string {
return c.Params.String(key)
}
Expand Down Expand Up @@ -297,9 +298,10 @@ func (c *Context) FormParams(excepts ...[]string) (url.Values, error) {

// 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)
//
// 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 (c *Context) ParseMultipartForm(maxMemory ...int) error {
max := defaultMaxMemory
if len(maxMemory) > 0 {
Expand Down Expand Up @@ -349,26 +351,28 @@ func (c *Context) SaveFile(file *multipart.FileHeader, dst string) error {
// 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"
//
// // record value to Request.ctx
// r := c.Req
// c.Req = r.WithContext(context.WithValue(r.Context(), "key", "value"))
// // ...
// val := c.ReqCtxValue("key") // "value"
func (c *Context) ReqCtxValue(key interface{}) interface{} {
return c.Req.Context().Value(key)
}

// WithReqCtxValue with request ctx Value.
// Usage:
// ctx.WithReqCtxValue()
//
// ctx.WithReqCtxValue()
func (c *Context) WithReqCtxValue(key, val interface{}) {
r := c.Req
c.Req = r.WithContext(context.WithValue(r.Context(), key, val))
}

// RawBodyData get raw body data
func (c *Context) RawBodyData() ([]byte, error) {
return ioutil.ReadAll(c.Req.Body)
return io.ReadAll(c.Req.Body)
}

/*************************************************************
Expand Down
26 changes: 17 additions & 9 deletions dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,20 @@ var internal405Handler HandlerFunc = func(c *Context) {
*************************************************************/

// Listen quick create a HTTP server with the router
//
// Usage:
//
// r.Listen("8090")
// r.Listen("IP:PORT")
func (r *Router) Listen(addr ...string) {
var err error
defer func() { debugPrintError(err) }()
defer func() {
debugPrintError(r.err)
}()

address := resolveAddress(addr)

fmt.Printf("Serve listen on %s. Go to http://%s\n", address, address)
err = http.ListenAndServe(address, r)
r.err = http.ListenAndServe(address, r)
}

// ListenTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
Expand All @@ -59,7 +65,7 @@ func (r *Router) ListenTLS(addr, certFile, keyFile string) {
}

// ListenUnix attaches the router to a http.Server and starts listening and serving HTTP requests
// through the specified unix socket (ie. a file)
// through the specified unix socket (i.e. a file)
func (r *Router) ListenUnix(file string) {
var err error
defer func() { debugPrintError(err) }()
Expand All @@ -80,12 +86,14 @@ func (r *Router) ListenUnix(file string) {
}

// WrapHTTPHandlers apply some pre http handlers for the router.
//
// Usage:
// import "github.com/gookit/rux/handlers"
// r := rux.New()
// // ... add routes
// handler := r.WrapHTTPHandlers(handlers.HTTPMethodOverrideHandler)
// http.ListenAndServe(":8080", handler)
//
// import "github.com/gookit/rux/handlers"
// r := rux.New()
// // ... add routes
// handler := r.WrapHTTPHandlers(handlers.HTTPMethodOverrideHandler)
// http.ListenAndServe(":8080", handler)
func (r *Router) WrapHTTPHandlers(preHandlers ...func(h http.Handler) http.Handler) http.Handler {
var wrapped http.Handler
max := len(preHandlers)
Expand Down
4 changes: 2 additions & 2 deletions extends.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ func (c *Context) Render(status int, name string, data interface{}) (err error)
}

// Validate context validator
// Deprecated
// please use ShouldBind() instead, it will auto call validator.
//
// Deprecated: please use ShouldBind() instead, it will auto call validator.
func (c *Context) Validate(i interface{}) error {
if c.Router().Validator == nil {
return errors.New("validator not registered")
Expand Down
9 changes: 8 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/gookit/rux

go 1.16
go 1.18

require (
github.com/gookit/color v1.5.2
Expand All @@ -9,3 +9,10 @@ require (
github.com/gorilla/websocket v1.5.0
github.com/monoculum/formam v3.5.5+incompatible
)

require (
github.com/gookit/filter v1.1.4 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
)
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gookit/color v1.5.2 h1:uLnfXcaFjlrDnQDT+NCBcfhrXqYTx/rcCa6xn01Y8yI=
github.com/gookit/color v1.5.2/go.mod h1:w8h4bGiHeeBpvQVePTutdbERIUf3oJE5lZ8HM0UgXyg=
github.com/gookit/filter v1.1.4 h1:SXd6PEumiP/0jtF2crQRaz1wmKwHbW9xg5Ds6/ZP16w=
Expand Down Expand Up @@ -32,7 +31,6 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
Expand All @@ -41,7 +39,6 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand All @@ -57,7 +54,6 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
Expand Down
7 changes: 7 additions & 0 deletions render/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ type JSONRenderer struct {
NotEscape bool
}

// NewJSONIndented instance
func NewJSONIndented() JSONRenderer {
return JSONRenderer{
Indent: PrettyIndent,
}
}

// Render JSON to client
func (r JSONRenderer) Render(w http.ResponseWriter, obj interface{}) (err error) {
writeContentType(w, httpctype.JSON)
Expand Down
50 changes: 30 additions & 20 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
type Router struct {
// router name
Name string
// server start error
err error
// count routes
counter int
// context pool
Expand Down Expand Up @@ -96,22 +98,23 @@ type Router struct {
// Extends tools
//
// Renderer template(view) interface
// Deprecated
// Deprecated: will be removed
Renderer Renderer
// Validator validator interface
// Deprecated
// Deprecated: will be removed
Validator Validator
}

// New router instance, can with some options.
// Quick start:
// r := New()
// r.GET("/path", MyAction)
//
// r := New()
// r.GET("/path", MyAction)
//
// With options:
// r := New(EnableCaching, MaxNumCaches(1000))
// r.GET("/path", MyAction)
//
// r := New(EnableCaching, MaxNumCaches(1000))
// r.GET("/path", MyAction)
func New(options ...func(*Router)) *Router {
router := &Router{
Name: "default",
Expand Down Expand Up @@ -203,8 +206,9 @@ func (r *Router) Any(path string, handler HandlerFunc, middles ...HandlerFunc) {

// Add a route to router, allow set multi method
// Usage:
// r.Add("/path", myHandler)
// r.Add("/path1", myHandler, "GET", "POST")
//
// r.Add("/path", myHandler)
// r.Add("/path1", myHandler, "GET", "POST")
func (r *Router) Add(path string, handler HandlerFunc, methods ...string) *Route {
route := NewRoute(path, handler, methods...)
return r.AddRoute(route)
Expand Down Expand Up @@ -261,15 +265,14 @@ func (r *Router) Controller(basePath string, controller ControllerFace, middles

// 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
//
// 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 (r *Router) Resource(basePath string, controller interface{}, middles ...HandlerFunc) {
cv := reflect.ValueOf(controller)
ct := cv.Type()
Expand Down Expand Up @@ -369,8 +372,9 @@ func (r *Router) StaticFS(prefixURL string, fs http.FileSystem) {
// StaticDir add a static asset file handle
//
// Usage:
// r.StaticDir("/assets", "/static")
// // access GET /assets/css/site.css -> will find /static/css/site.css
//
// r.StaticDir("/assets", "/static")
// // access GET /assets/css/site.css -> will find /static/css/site.css
func (r *Router) StaticDir(prefixURL string, fileDir string) {
fsHandler := http.StripPrefix(prefixURL, http.FileServer(http.Dir(fileDir)))

Expand All @@ -383,7 +387,8 @@ func (r *Router) StaticDir(prefixURL string, fileDir string) {
// StaticFiles static files from the given file system root. and allow limit extensions.
//
// Usage:
// router.ServeFiles("/src", "/var/www", "css|js|html")
//
// router.ServeFiles("/src", "/var/www", "css|js|html")
//
// Notice: if the rootDir is relation path, it is relative the server runtime dir.
func (r *Router) StaticFiles(prefixURL string, rootDir string, exts string) {
Expand Down Expand Up @@ -562,3 +567,8 @@ func (r *Router) appendGroupInfo(route *Route) {
// re-set formatted path
route.path = path
}

// Err get
func (r *Router) Err() error {
return r.err
}
8 changes: 8 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package rux

// Server struct
type Server struct {
Router
// server start error
err error
}

0 comments on commit 8908e05

Please sign in to comment.