rux

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2023 License: MIT Imports: 26 Imported by: 17

README

Rux

GitHub go.mod Go version Actions Status GitHub tag (latest SemVer) GoDoc Coverage Status Go Report Card

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()
	
	// Add Routes:
	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")
	})
	// add multi method support for an route path
	r.Add("/post[/{id}]", func(c *rux.Context) {
		if c.Param("id") == "" {
			// do create post
			c.Text(200, "created")
			return
		}

		id := c.Params.Int("id")
		// do update post
		c.Text(200, "updated " + fmt.Sprint(id))
	}, rux.POST, rux.PUT)

	// Start server
	r.Listen(":8080")
	// can also
	// http.ListenAndServe(":8080", r)
}

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+}

// can access by: "/blog/123"
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}]:

// can access by: "/blog/my-article" "/blog/my-article.html"
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") == "" {
        // do create post
        c.Text(200, "created")
        return
    }

    id := c.Params.Int("id")
    // do update post
    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()
	
	// add global middleware
	r.Use(func(c *rux.Context) {
	    // do something ...
	})
	
	// add middleware for the route
	route := r.GET("/middle", func(c *rux.Context) { // main handler
		c.WriteString("-O-")
	}, func(c *rux.Context) { // middle 1
        c.WriteString("a")
        c.Next() // Notice: call Next()
        c.WriteString("A")
        // if call Abort(), will abort at the end of this middleware run
        // c.Abort() 
    })
	
	// add more by Use()
	route.Use(func(c *rux.Context) { // middle 2
		c.WriteString("b")
		c.Next()
		c.WriteString("B")
	})

	// now, access the URI /middle
	// will output: ab-O-BA
}
  • 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"
	// here we use gorilla/handlers, it provides some generic handlers.
	"github.com/gorilla/handlers"
)

func main() {
	r := rux.New()
	
	// create a simple generic http.Handler
	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")
	})
	// add routes ...
	
    // Wrap our server with our gzip handler to gzip compress all responses.
    http.ListenAndServe(":8000", handlers.CompressHandler(r))
}

More Usage

Static Assets
package main

import (
	"embed"	
	"net/http"

	"github.com/gookit/rux"
)

//go:embed static
var embAssets embed.FS

func main() {
	r := rux.New()

	// one file
	r.StaticFile("/site.js", "testdata/site.js")

	// allow any files in the directory.
	r.StaticDir("/static", "testdata")

	// file type limit in the directory
	r.StaticFiles("/assets", "testdata", "css|js")

	// go 1.16+: use embed assets. access: /embed/static/some.html
	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()
	
	// Method 1
	myRoute := rux.NewNamedRoute("name1", "/path4/some/{id}", emptyHandler, "GET")
	r.AddRoute(myRoute)

	// Method 2
	rux.AddNamed("name2", "/", func(c *rux.Context) {
		c.Text(200, "hello")
	})

	// Method 3
	r.GET("/hi", func(c *rux.Context) {
		c.Text(200, "hello")
	}).NamedTo("name3", r)
	
	// get route by name
	myRoute = r.GetRoute("name1")
Redirect

redirect to other page

r.GET("/", func(c *rux.Context) {
    c.AbortThen().Redirect("/login", 302)
})

// Or
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") // "test-value1"
	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

// Implement the ServeHTTP method on our new type
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Check if a http.Handler is registered for the given host.
	// If yes, use it to handle the request.
	if router := hs[r.Host]; router != nil {
		router.ServeHTTP(w, r)
	} else {
		// Handle host names for which no handler is registered
		http.Error(w, "Forbidden", 403) // Or Redirect?
	}
}

func main() {
	// Initialize a router as usual
	router := rux.New()
	router.GET("/", Index)
	router.GET("/hello/{name}", func(c *rux.Context) {})

	// Make a new HostSwitch and insert the router (our http handler)
	// for example.com and port 12345
	hs := make(HostSwitch)
	hs["example.com:12345"] = router

	// Use the HostSwitch to listen and serve on port 12345
	log.Fatal(http.ListenAndServe(":12345", hs))
}
RESETFul Style
package main

import (
	"log"
	"net/http"

	"github.com/gookit/rux"
)

type Product struct {
}

// Uses middlewares [optional]
func (Product) Uses() map[string][]rux.HandlerFunc {
	return map[string][]rux.HandlerFunc{
		// function name: handlers
		"Delete": []rux.HandlerFunc{
			handlers.HTTPBasicAuth(map[string]string{"test": "123"}),
			handlers.GenRequestID(),
		},
	}
}

// all products [optional]
func (p *Product) Index(c *rux.Context) {
	// do something
}

// create product [optional]
func (p *Product) Create(c *rux.Context) {
	// do something
}

// save new product [optional]
func (p *Product) Store(c *rux.Context) {
	// do something
}

// show product with {id} [optional]
func (p *Product) Show(c *rux.Context) {
	// do something
}

// edit product [optional]
func (p *Product) Edit(c *rux.Context) {
	// do something
}

// save edited product [optional]
func (p *Product) Update(c *rux.Context) {
	// do something
}

// delete product [optional]
func (p *Product) Delete(c *rux.Context) {
	// do something
}

func main() {
	router := rux.New()

	// methods	Path	Action	Route Name
    // GET	/product	index	product_index
    // GET	/product/create	create	product_create
    // POST	/product	store	product_store
    // GET	/product/{id}	show	product_show
    // GET	/product/{id}/edit	edit	product_edit
    // PUT/PATCH	/product/{id}	update	product_update
    // DELETE	/product/{id}	delete	product_delete
    // resetful style
	router.Resource("/", new(Product))

	log.Fatal(http.ListenAndServe(":12345", router))
}
Controller Style
package main

import (
	"log"
	"net/http"

	"github.com/gookit/rux"
)

// News controller
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) {
	// Do something
}

func (n *News) Create(c *rux.Context) {
	// Do something
}

func (n *News) Edit(c *rux.Context) {
	// Do something
}

func main() {
	router := rux.New()

	// controller style
	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() {
	// Initialize a router as usual
	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.Scheme("https")
        // b.Host("www.mytest.com")
        b.Queries(u)
        b.Params(rux.M{"{category_id}": "100", "{new_id}": "20"})
		// b.Path("/dev")
        // println(b.Build().String())
        
        println(c.Router().BuildRequestURL("new_detail", b).String())
		// result:  /news/100/20/detail?username=admin&password=12345
		// get current route name
		if c.MustGet(rux.CTXCurrentRouteName) == "new_detail" {
            // post data etc....
        }
	}).NamedTo("new_detail", router)

	// Use the HostSwitch to listen and serve on port 12345
	log.Fatal(http.ListenAndServe(":12345", router))
}

Help

  • lint
golint ./...
  • format check
# list error files
gofmt -s -l ./
# fix format and write to file
gofmt -s -w some.go
  • unit test
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

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/gookit/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

Examples

Constants

View Source
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

View Source
const (
	// ContentType header key
	ContentType = "Content-Type"
	// ContentBinary represents content type application/octet-stream
	ContentBinary = "application/octet-stream"

	// ContentDisposition describes contentDisposition
	ContentDisposition = "Content-Disposition"
)
View Source
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

View Source
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 AllMethods

func AllMethods() []string

AllMethods get all methods

func AnyMethods added in v1.0.2

func AnyMethods() []string

AnyMethods get all methods

func CachingWithNum added in v1.2.8

func CachingWithNum(num uint16) func(*Router)

CachingWithNum for the router

func Debug

func Debug(val bool)

Debug switch debug mode

func EnableCaching

func EnableCaching(r *Router)

EnableCaching for the router

func GetGlobalVars

func GetGlobalVars() map[string]string

GetGlobalVars get all global path vars

func HandleFallbackRoute added in v1.3.0

func HandleFallbackRoute(r *Router)

HandleFallbackRoute enable for the router

func HandleMethodNotAllowed

func HandleMethodNotAllowed(r *Router)

HandleMethodNotAllowed enable for the router

func InterceptAll

func InterceptAll(path string) func(*Router)

InterceptAll setting for the router

func IsDebug

func IsDebug() bool

IsDebug return rux is debug mode.

func MaxNumCaches

func MaxNumCaches(num uint16) func(*Router)

MaxNumCaches setting for the router

func MethodsString added in v1.3.0

func MethodsString() string

MethodsString of all supported methods

func NewCachedRoutes added in v1.2.3

func NewCachedRoutes(size int) *cachedRoutes

NewCachedRoutes Get Cache pointer

func SetGlobalVar

func SetGlobalVar(name, regex string)

SetGlobalVar set an global path var

func StrictLastSlash

func StrictLastSlash(r *Router)

StrictLastSlash enable for the router

func UseEncodedPath

func UseEncodedPath(r *Router)

UseEncodedPath enable for the router

Types

type BuildRequestURL added in v1.1.5

type BuildRequestURL struct {
	// contains filtered or unexported fields
}

BuildRequestURL struct

func NewBuildRequestURL added in v1.1.5

func NewBuildRequestURL() *BuildRequestURL

NewBuildRequestURL get new obj

func (*BuildRequestURL) Build added in v1.1.5

func (b *BuildRequestURL) Build(withParams ...M) *url.URL

Build url

func (*BuildRequestURL) Host added in v1.1.5

func (b *BuildRequestURL) Host(host string) *BuildRequestURL

Host set Host

func (*BuildRequestURL) Params added in v1.1.5

func (b *BuildRequestURL) Params(params M) *BuildRequestURL

Params set Params

func (*BuildRequestURL) Path added in v1.1.5

func (b *BuildRequestURL) Path(path string) *BuildRequestURL

Path set Path

func (*BuildRequestURL) Queries added in v1.1.5

func (b *BuildRequestURL) Queries(queries url.Values) *BuildRequestURL

Queries set Queries

func (*BuildRequestURL) Scheme added in v1.1.5

func (b *BuildRequestURL) Scheme(scheme string) *BuildRequestURL

Scheme set Scheme

func (*BuildRequestURL) User added in v1.1.5

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

func (c *Context) AbortThen() *Context

AbortThen will abort at the end of this middleware run, and return context to continue.

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int, msg ...string)

AbortWithStatus calls `Abort()` and writes the headers with the specified status code.

func (*Context) AcceptedTypes added in v1.1.0

func (c *Context) AcceptedTypes() []string

AcceptedTypes get Accepted Types.

func (*Context) AddError added in v1.1.4

func (c *Context) AddError(err error)

AddError add a error to context

func (*Context) Attachment

func (c *Context) Attachment(srcFile, outName string)

Attachment a file to response.

Usage:

c.Attachment("path/to/some.zip", "new-name.zip")

func (*Context) AutoBind added in v1.3.0

func (c *Context) AutoBind(obj any) error

AutoBind auto bind request data to a struct, will auto select binding.Binder by content-type

Usage:

err := c.AutoBind(&user)

func (*Context) Back added in v1.1.5

func (c *Context) Back(optionalCode ...int)

Back redirect to referer url

func (*Context) Binary

func (c *Context) Binary(status int, in io.ReadSeeker, outName string, inline bool)

Binary serve data as Binary response.

Usage:

in, _ := os.Open("./README.md")
r.Binary(http.StatusOK, in, "readme.md", true)

func (*Context) Bind added in v1.1.5

func (c *Context) Bind(obj any) error

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 added in v1.3.0

func (c *Context) BindForm(obj any) error

BindForm request data to an struct, will auto call validator

Usage:

err := c.BindForm(&user)

func (*Context) BindJSON added in v1.3.0

func (c *Context) BindJSON(obj any) error

BindJSON request data to an struct, will auto call validator

Usage:

err := c.BindJSON(&user)

func (*Context) BindXML added in v1.3.0

func (c *Context) BindXML(obj any) error

BindXML request data to an struct, will auto call validator

Usage:

err := c.BindXML(&user)

func (*Context) Blob added in v1.2.2

func (c *Context) Blob(status int, contentType string, data []byte)

Blob writes out []byte

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP implements a best effort algorithm to return the real client IP

func (*Context) ContentType added in v1.1.0

func (c *Context) ContentType() string

ContentType get content type.

func (*Context) Cookie added in v1.1.0

func (c *Context) Cookie(name string) string

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) Copy

func (c *Context) Copy() *Context

Copy a new context

func (*Context) Data added in v1.0.1

func (c *Context) Data() map[string]any

Data get all context data

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

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) DelCookie added in v1.2.9

func (c *Context) DelCookie(names ...string)

DelCookie by given names

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

func (c *Context) Err() error

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 added in v1.1.2

func (c *Context) FastSetCookie(name, value string, maxAge int)

FastSetCookie Quick Set Cookie

func (*Context) File

func (c *Context) File(filePath string)

File writes the specified file into the body stream in a efficient way.

func (*Context) FileContent

func (c *Context) FileContent(file string, names ...string)

FileContent serves given file as text content to response.

func (*Context) FirstError added in v1.1.3

func (c *Context) FirstError() error

FirstError get first error

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 added in v1.2.4

func (c *Context) FormParams(excepts ...[]string) (url.Values, error)

FormParams return body values

func (*Context) Get

func (c *Context) Get(key string) (v any, ok bool)

Get a value from context data

func (*Context) HTML

func (c *Context) HTML(status int, data []byte)

HTML writes out as html text. if data is empty, only write headers

func (*Context) HTTPError

func (c *Context) HTTPError(msg string, status int)

HTTPError response

func (*Context) Handler

func (c *Context) Handler() HandlerFunc

Handler returns the main handler.

func (*Context) HandlerName

func (c *Context) HandlerName() string

HandlerName get the main handler name

func (*Context) Header

func (c *Context) Header(key string) string

Header return header value by key

func (*Context) Init

func (c *Context) Init(w http.ResponseWriter, r *http.Request)

Init a context

func (*Context) Inline

func (c *Context) Inline(srcFile, outName string)

Inline file content.

Usage:

c.Inline("testdata/site.md", "new-name.md")

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax check request is ajax request

func (*Context) IsGet added in v1.2.0

func (c *Context) IsGet() bool

IsGet check request is post request

func (*Context) IsMethod

func (c *Context) IsMethod(method string) bool

IsMethod returns true if current is equal to input method name

func (*Context) IsPost added in v1.1.5

func (c *Context) IsPost() bool

IsPost check request is post request

func (*Context) IsTLS

func (c *Context) IsTLS() bool

IsTLS request check

func (*Context) IsWebSocket

func (c *Context) IsWebSocket() bool

IsWebSocket returns true if the request headers indicate that a webSocket handshake is being initiated by the client.

func (*Context) JSON

func (c *Context) JSON(status int, obj any)

JSON writes out a JSON response.

func (*Context) JSONBytes

func (c *Context) JSONBytes(status int, bs []byte)

JSONBytes writes out a string as JSON response.

func (*Context) JSONP added in v1.2.1

func (c *Context) JSONP(status int, callback string, obj any)

JSONP is JSONP response.

func (*Context) Length added in v1.2.7

func (c *Context) Length() int

Length get length from the response

func (*Context) MustBind added in v1.3.0

func (c *Context) MustBind(obj any, binder binding.Binder)

MustBind bind request data to a struct, will auto call validator

Usage:

c.MustBind(&user, binding.Json)

func (*Context) MustRender added in v1.3.0

func (c *Context) MustRender(status int, obj any, renderer render.Renderer)

MustRender render and response to client

func (*Context) Next

func (c *Context) Next()

Next processing, run all handlers

func (*Context) NoContent

func (c *Context) NoContent()

NoContent serve success but no content response

func (*Context) Param

func (c *Context) Param(key string) string

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

func (c *Context) ParseMultipartForm(maxMemory ...int) 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)

func (*Context) Post

func (c *Context) Post(key string, defVal ...string) string

Post return body value by key, and allow with default value

func (*Context) PostParam

func (c *Context) PostParam(key string) (string, bool)

PostParam return body value by key

func (*Context) PostParams

func (c *Context) PostParams(key string) ([]string, bool)

PostParams return body values by key

func (*Context) Query

func (c *Context) Query(key string, defVal ...string) string

Query return query value by key, and allow with default value

func (*Context) QueryParam

func (c *Context) QueryParam(key string) (string, bool)

QueryParam return query value by key

func (*Context) QueryParams

func (c *Context) QueryParams(key string) ([]string, bool)

QueryParams return query values by key

func (*Context) QueryValues

func (c *Context) QueryValues() url.Values

QueryValues get URL query data

func (*Context) RawBodyData added in v1.1.0

func (c *Context) RawBodyData() ([]byte, error)

RawBodyData get raw body data

func (*Context) RawWriter added in v1.1.0

func (c *Context) RawWriter() http.ResponseWriter

RawWriter get raw http.ResponseWriter instance

func (*Context) Redirect

func (c *Context) Redirect(path string, optionalCode ...int)

Redirect other URL with status code(3xx e.g 301, 302).

func (*Context) Render added in v1.1.5

func (c *Context) Render(status int, name string, data any) (err error)

Render html template.

please use ShouldRender() instead

func (*Context) ReqCtxValue

func (c *Context) ReqCtxValue(key any) any

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) Reset

func (c *Context) Reset()

Reset context data

func (*Context) Respond added in v1.3.0

func (c *Context) Respond(status int, obj any, renderer render.Renderer)

Respond render and response to client

func (*Context) Router

func (c *Context) Router() *Router

Router get router instance

func (*Context) SafeGet added in v1.4.0

func (c *Context) SafeGet(key string) any

SafeGet a value from context data

func (*Context) SaveFile

func (c *Context) SaveFile(file *multipart.FileHeader, dst string) error

SaveFile uploads the form file to specific dst.

func (*Context) Set

func (c *Context) Set(key string, val any)

Set a value to context by key. Usage:

c.Set("key", "value")
// ...
val := c.Get("key") // "value"

func (*Context) SetCookie added in v1.1.0

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) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader for the response

func (*Context) SetStatus

func (c *Context) SetStatus(status int)

SetStatus code for the response

func (*Context) SetStatusCode added in v1.1.4

func (c *Context) SetStatusCode(status int)

SetStatusCode code for the response. alias of the SetStatus()

func (*Context) ShouldBind added in v1.3.0

func (c *Context) ShouldBind(obj any, binder binding.Binder) error

ShouldBind bind request data to a struct, will auto call validator

Usage:

err := c.ShouldBind(&user, binding.JSON)

func (*Context) ShouldRender added in v1.3.0

func (c *Context) ShouldRender(status int, obj any, renderer render.Renderer) error

ShouldRender render and response to client

func (*Context) StatusCode added in v1.1.0

func (c *Context) StatusCode() int

StatusCode get status code from the response

func (*Context) Stream added in v1.1.0

func (c *Context) Stream(status int, contentType string, r io.Reader)

Stream writes out io.Reader

func (*Context) Text

func (c *Context) Text(status int, str string)

Text writes out a string as plain text.

func (*Context) URL

func (c *Context) URL() *url.URL

URL get URL instance from request

func (*Context) UploadFile

func (c *Context) UploadFile(name string, saveAs string) error

UploadFile handle upload file and save as local file

func (*Context) Validate added in v1.1.5

func (c *Context) Validate(obj any) error

Validate input struct or map data. should call Bind() before validate.

Recommended use ShouldBind() instead, it will binding and validate.

func (*Context) Value

func (c *Context) Value(key any) any

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

func (c *Context) WithReqCtxValue(key, val any)

WithReqCtxValue with request ctx Value.

Usage:

ctx.WithReqCtxValue()

func (*Context) WriteBytes added in v1.1.0

func (c *Context) WriteBytes(bt []byte)

WriteBytes write byte data to response, will panic on error.

func (*Context) WriteString

func (c *Context) WriteString(str string)

WriteString write string to response

func (*Context) XML added in v1.2.1

func (c *Context) XML(status int, obj any, indents ...string)

XML output xml response.

type ControllerFace added in v1.1.3

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 added in v1.3.0

func HTTPHandler(gh http.Handler) HandlerFunc

HTTPHandler warp a generic http.Handler as an rux HandlerFunc

func HTTPHandlerFunc added in v1.3.0

func HTTPHandlerFunc(hf http.HandlerFunc) HandlerFunc

HTTPHandlerFunc warp a generic http.HandlerFunc as a rux HandlerFunc

func WrapH added in v1.3.3

func WrapH(hh http.Handler) HandlerFunc

WrapH warp an generic http.Handler as an rux HandlerFunc

func WrapHF added in v1.3.3

func WrapHF(hf http.HandlerFunc) HandlerFunc

WrapHF warp a generic http.HandlerFunc as a rux HandlerFunc

func WrapHTTPHandler added in v1.1.0

func WrapHTTPHandler(gh http.Handler) HandlerFunc

WrapHTTPHandler warp a generic http.Handler as an rux HandlerFunc

func WrapHTTPHandlerFunc added in v1.1.0

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 M

type M map[string]any

M a short name for `map[string]any`

type Params

type Params map[string]string

Params for current route

func (Params) Has

func (p Params) Has(key string) bool

Has param key in the Params

func (Params) Int

func (p Params) Int(key string) (val int)

Int get int value by key

func (Params) String

func (p Params) String(key string) (val string)

String get string value by key

type Renderer added in v1.1.5

type Renderer interface {
	Render(io.Writer, string, any, *Context) error
}

Renderer interface

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 added in v1.2.1

func NamedRoute(name, path string, handler HandlerFunc, methods ...string) *Route

NamedRoute create a new route with name. alias of NewNamedRoute()

func NewNamedRoute added in v1.1.5

func NewNamedRoute(name, path string, handler HandlerFunc, methods ...string) *Route

NewNamedRoute create a new route with name

func NewRoute added in v1.1.0

func NewRoute(path string, handler HandlerFunc, methods ...string) *Route

NewRoute create a new route

func (*Route) AttachTo added in v1.1.0

func (r *Route) AttachTo(router *Router)

AttachTo register the route to router.

func (*Route) Handler

func (r *Route) Handler() HandlerFunc

Handler returns the main handler.

func (*Route) HandlerName

func (r *Route) HandlerName() string

HandlerName get the main handler name

func (*Route) Handlers added in v1.3.0

func (r *Route) Handlers() HandlersChain

Handlers returns handlers of the route.

func (*Route) Info added in v1.1.0

func (r *Route) Info() RouteInfo

Info get basic info of the route

func (*Route) MethodString added in v1.2.0

func (r *Route) MethodString(char string) string

MethodString join allowed methods to an string

func (*Route) Methods added in v1.2.0

func (r *Route) Methods() []string

Methods get route allowed request methods

func (*Route) Name added in v1.1.0

func (r *Route) Name() string

Name get route name

func (*Route) NamedTo added in v1.1.0

func (r *Route) NamedTo(name string, router *Router)

NamedTo add name and register the route to router.

func (*Route) Path added in v1.1.0

func (r *Route) Path() string

Path get route path string.

func (*Route) String

func (r *Route) String() string

String route info to string

func (*Route) ToURL added in v1.3.0

func (r *Route) ToURL(buildArgs ...any) *url.URL

ToURL build request URL, can with path vars

func (*Route) Use

func (r *Route) Use(middleware ...HandlerFunc) *Route

Use add middleware handlers to the route

type RouteInfo added in v1.1.0

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

func New(options ...func(*Router)) *Router

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 added in v1.2.1

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) AddRoute added in v1.1.0

func (r *Router) AddRoute(route *Route) *Route

AddRoute add a route by Route instance. , methods ...string

func (*Router) Any

func (r *Router) Any(path string, handler HandlerFunc, middles ...HandlerFunc)

Any add route and allow any request methods

func (*Router) BuildRequestURL added in v1.1.5

func (r *Router) BuildRequestURL(name string, buildArgs ...any) *url.URL

BuildRequestURL alias of the method BuildRequestURL()

func (*Router) BuildURL added in v1.2.5

func (r *Router) BuildURL(name string, buildArgs ...any) *url.URL

BuildURL build Request URL one arg can be set buildRequestURL or rux.M

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) Err added in v1.4.0

func (r *Router) Err() error

Err get

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) GetRoute added in v1.1.0

func (r *Router) GetRoute(name string) *Route

GetRoute get a named route.

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 added in v1.1.0

func (r *Router) HandleContext(c *Context)

HandleContext handle a given context

func (*Router) Handlers added in v1.2.1

func (r *Router) Handlers() HandlersChain

Handlers get global handlers

func (*Router) IterateRoutes added in v1.1.0

func (r *Router) IterateRoutes(fn func(route *Route))

IterateRoutes iterate all routes

func (*Router) Listen

func (r *Router) Listen(addr ...string)

Listen quick create a HTTP server with the router

Usage:

r.Listen("8090")
r.Listen("IP:PORT")
r.Listen("IP", "PORT")

func (*Router) ListenTLS

func (r *Router) ListenTLS(addr, certFile, keyFile string)

ListenTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.

func (*Router) ListenUnix

func (r *Router) ListenUnix(file string)

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

func (r *Router) Match(method, path string) (route *Route, ps Params, alm []string)

Match route by given request METHOD and URI path

ps - route path Params, when has path vars. alm - allowed request methods

func (*Router) NamedRoutes added in v1.2.6

func (r *Router) NamedRoutes() map[string]*Route

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 added in v1.3.3

func (r *Router) QuickMatch(method, path string) (route *Route, ps Params, alm []string)

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 added in v1.2.4

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) Routes added in v1.1.0

func (r *Router) Routes() (rs []RouteInfo)

Routes get all route basic info

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")
Output:

func (*Router) StaticDir

func (r *Router) StaticDir(prefixURL string, fileDir string)

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 added in v1.0.1

func (r *Router) StaticFS(prefixURL string, fs http.FileSystem)

StaticFS add a file system handle.

func (*Router) StaticFile

func (r *Router) StaticFile(path, filePath string)

StaticFile add a static asset file handle

func (*Router) StaticFiles

func (r *Router) StaticFiles(prefixURL string, rootDir string, exts string)

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

func (r *Router) StaticFunc(path string, handler func(c *Context))

StaticFunc add a static asset file handle

func (*Router) String

func (r *Router) String() string

String convert all routes to string

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

func (r *Router) WithOptions(options ...func(*Router))

WithOptions for the router

func (*Router) WrapHTTPHandlers added in v1.1.0

func (r *Router) WrapHTTPHandlers(preHandlers ...func(h http.Handler) http.Handler) http.Handler

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)

type Validator added in v1.1.5

type Validator interface {
	Validate(i any) error
}

Validator interface

Directories

Path Synopsis
pkg
binding
Package binding provide some common binder for binding http.Request data to strcut
Package binding provide some common binder for binding http.Request data to strcut
websocket
Package websocket utils
Package websocket utils

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL