Documentation
¶
Overview ¶
Package router 0.6.5 provides fast HTTP request router.
The router matches incoming requests by the request method and the path. If a handle is registered for this path and method, the router delegates the request to defined handler. The router package is useful to prepare a RESTful API for Go services. It has JSON output, which bind automatically for relevant type of data. The router has timer feature to display duration of request handling in the header
Simplest example (serve static route):
package main import ( "github.com/takama/router" ) func Hello(c *router.Control) { c.Body("Hello") } func main() { r := router.New() r.GET("/hello", Hello) // Listen and serve on 0.0.0.0:8888 r.Listen(":8888") }
Check it:
curl -i http://localhost:8888/hello
Serve dynamic route with parameter:
func main() { r := router.New() r.GET("/hello/:name", func(c *router.Control) { c.Code(200).Body("Hello " + c.Get(":name")) }) // Listen and serve on 0.0.0.0:8888 r.Listen(":8888") }
Checks JSON Content-Type automatically:
// Data is helper to construct JSON type Data map[string]interface{} func main() { r := router.New() r.GET("/settings/database/:db", func(c *router.Control) { data := map[string]map[string]string{ "Database settings": { "database": c.Get(":db"), "host": "localhost", "port": "3306", }, } c.Code(200).Body(data) }) // Listen and serve on 0.0.0.0:8888 r.Listen(":8888") }
Custom handler with "Access-Control-Allow" options and compact JSON:
// Data is helper to construct JSON type Data map[string]interface{} func baseHandler(handle router.Handle) router.Handle { return func(c *router.Control) { c.CompactJSON(true) if origin := c.Request.Header.Get("Origin"); origin != "" { c.Writer.Header().Set("Access-Control-Allow-Origin", origin) c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") } handle(c) } } func Info(c *router.Control) { data := Data{ "debug": true, "error": false, } c.Body(data) } func main() { r := router.New() r.CustomHandler = baseHandler r.GET("/info", Info) // Listen and serve on 0.0.0.0:8888 r.Listen(":8888") }
Use google json style `https://google.github.io/styleguide/jsoncstyleguide.xml`
func main() { r := router.New() r.GET("/api/v1/people/:action/:id", func(c *router.Control) { // Do something c.Method("people." + c.Get(":action")) c.SetParams(map[string]string{"userId": c.Get(":id")}) c.SetError(http.StatusNotFound, "UserId not found") c.AddError(router.Error{Message: "Group or User not found"}) c.Code(http.StatusNotFound).Body(nil) }) // Listen and serve on 0.0.0.0:8888 r.Listen(":8888") }
Go Router
Index ¶
- Constants
- type Control
- func (c *Control) APIVersion(version string) *Control
- func (c *Control) AddError(errors ...Error) *Control
- func (c *Control) Body(data interface{})
- func (c *Control) Code(code int) *Control
- func (c *Control) CompactJSON(mode bool) *Control
- func (c *Control) Get(name string) string
- func (c *Control) GetCode() int
- func (c *Control) GetTimer() time.Time
- func (c *Control) HeaderContext(context string) *Control
- func (c *Control) ID(id string) *Control
- func (c *Control) Method(method string) *Control
- func (c *Control) Set(params ...Param) *Control
- func (c *Control) SetError(code uint16, message string) *Control
- func (c *Control) SetParams(params interface{}) *Control
- func (c *Control) UseMetaData() *Control
- func (c *Control) UseTimer()
- type Error
- type ErrorHeader
- type Handle
- type Header
- type Param
- type Route
- type Router
- func (r *Router) AllowedMethods(path string) []string
- func (r *Router) DELETE(path string, h Handle)
- func (r *Router) GET(path string, h Handle)
- func (r *Router) HEAD(path string, h Handle)
- func (r *Router) Handle(method, path string, h Handle)
- func (r *Router) Handler(method, path string, handler http.Handler)
- func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
- func (r *Router) Listen(hostPort string)
- func (r *Router) Lookup(method, path string) (Handle, []Param, bool)
- func (r *Router) OPTIONS(path string, h Handle)
- func (r *Router) PATCH(path string, handle Handle)
- func (r *Router) POST(path string, h Handle)
- func (r *Router) PUT(path string, h Handle)
- func (r *Router) Routes() []Route
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
Constants ¶
const ( // MIMEJSON - "Content-type" for JSON MIMEJSON = "application/json" // MIMETEXT - "Content-type" for TEXT MIMETEXT = "text/plain" )
Default content types
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Control ¶
type Control struct { // Context embedded context.Context // Request is an adapter which allows the usage of a http.Request as standard request Request *http.Request // Writer is an adapter which allows the usage of a http.ResponseWriter as standard writer Writer http.ResponseWriter // User content type ContentType string // contains filtered or unexported fields }
Control allows us to pass variables between middleware, assign Http codes and render a Body.
func (*Control) APIVersion ¶
APIVersion adds API version meta data
func (*Control) Body ¶
func (c *Control) Body(data interface{})
Body renders the given data into the response body
func (*Control) CompactJSON ¶
CompactJSON changes JSON output format (default mode is false)
func (*Control) Get ¶
Get returns the first value associated with the given name. If there are no values associated with the key, an empty string is returned.
func (*Control) HeaderContext ¶
HeaderContext adds context meta data
func (*Control) UseMetaData ¶
UseMetaData shows meta data in JSON Header
type Error ¶
type Error struct { Domain string `json:"domain,omitempty"` Reason string `json:"reason,omitempty"` Message string `json:"message,omitempty"` Location string `json:"location,omitempty"` LocationType string `json:"locationType,omitempty"` ExtendedHelp string `json:"extendedHelp,omitempty"` SendReport string `json:"sendReport,omitempty"` }
Error report format
type ErrorHeader ¶
type ErrorHeader struct { Code uint16 `json:"code,omitempty"` Message string `json:"message,omitempty"` Errors []Error `json:"errors,omitempty"` }
ErrorHeader contains error code, message and array of specified error reports
type Header ¶
type Header struct { Duration time.Duration `json:"duration,omitempty"` Took string `json:"took,omitempty"` APIVersion string `json:"apiVersion,omitempty"` Context string `json:"context,omitempty"` ID string `json:"id,omitempty"` Method string `json:"method,omitempty"` Params interface{} `json:"params,omitempty"` Data interface{} `json:"data,omitempty"` Error interface{} `json:"error,omitempty"` }
Header is used to prepare a JSON header with meta data
type Router ¶
type Router struct { // NotFound is called when unknown HTTP method or a handler not found. // If it is not set, http.NotFound is used. // Please overwrite this if need your own NotFound handler. NotFound Handle // PanicHandler is called when panic happen. // The handler prevents your server from crashing and should be used to return // http status code http.StatusInternalServerError (500) PanicHandler Handle // CustomHandler is called allways if defined CustomHandler func(Handle) Handle // Logger activates logging user function for each requests Logger Handle // contains filtered or unexported fields }
Router represents a multiplexer for HTTP requests.
func (*Router) AllowedMethods ¶
AllowedMethods returns list of allowed methods
func (*Router) HandlerFunc ¶
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
HandlerFunc allows the usage of an http.HandlerFunc as a request handle.