Documentation
¶
Overview ¶
Package routing provides high performance and powerful HTTP routing capabilities.
Example ¶
router := routing.New()
router.Use(
// all these handlers are shared by every route
access.Logger(log.Printf),
slash.Remover(http.StatusMovedPermanently),
fault.Recovery(log.Printf),
)
// serve RESTful APIs
api := router.Group("/api")
api.Use(
// these handlers are shared by the routes in the api group only
content.TypeNegotiator(content.JSON, content.XML),
)
api.Get("/users", func(c *routing.Context) error {
return c.Write("user list")
})
api.Post("/users", func(c *routing.Context) error {
return c.Write("create a new user")
})
api.Put(`/users/<id:\d+>`, func(c *routing.Context) error {
return c.Write("update user " + c.Param("id"))
})
// serve index file
router.Get("/", file.Content("ui/index.html"))
// serve files under the "ui" subdirectory
router.Get("/*", file.Server(file.PathMap{
"/": "/ui/",
}))
http.Handle("/", router)
http.ListenAndServe(":8080", nil)
Index ¶
- Constants
- Variables
- func MethodNotAllowedHandler(c *Context) error
- func NotFoundHandler(*Context) error
- func ReadFormData(form map[string][]string, data interface{}) error
- type Context
- func (c *Context) Abort()
- func (c *Context) Form(key string, defaultValue ...string) string
- func (c *Context) Get(name string) interface{}
- func (c *Context) Next() error
- func (c *Context) Param(name string) string
- func (c *Context) PostForm(key string, defaultValue ...string) string
- func (c *Context) Query(name string, defaultValue ...string) string
- func (c *Context) Read(data interface{}) error
- func (c *Context) Router() *Router
- func (c *Context) Set(name string, value interface{})
- func (c *Context) SetDataWriter(writer DataWriter)
- func (c *Context) SetParam(name, value string)
- func (c *Context) URL(route string, pairs ...interface{}) string
- func (c *Context) Write(data interface{}) error
- type DataReader
- type DataWriter
- type FormDataReader
- type HTTPError
- type Handler
- type JSONDataReader
- type Route
- func (r *Route) Connect(handlers ...Handler) *Route
- func (r *Route) Delete(handlers ...Handler) *Route
- func (r *Route) Get(handlers ...Handler) *Route
- func (r *Route) Head(handlers ...Handler) *Route
- func (r *Route) Method() string
- func (r *Route) Name(name string) *Route
- func (r *Route) Options(handlers ...Handler) *Route
- func (r *Route) Patch(handlers ...Handler) *Route
- func (r *Route) Path() string
- func (r *Route) Post(handlers ...Handler) *Route
- func (r *Route) Put(handlers ...Handler) *Route
- func (r *Route) String() string
- func (r *Route) Tag(value interface{}) *Route
- func (r *Route) Tags() []interface{}
- func (r *Route) To(methods string, handlers ...Handler) *Route
- func (r *Route) Trace(handlers ...Handler) *Route
- func (r *Route) URL(pairs ...interface{}) (s string)
- type RouteGroup
- func (rg *RouteGroup) Any(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Connect(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Delete(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Get(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Group(prefix string, handlers ...Handler) *RouteGroup
- func (rg *RouteGroup) Head(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Options(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Patch(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Post(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Put(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) To(methods, path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Trace(path string, handlers ...Handler) *Route
- func (rg *RouteGroup) Use(handlers ...Handler)
- type Router
- func (r *Router) Find(method, path string) (handlers []Handler, params map[string]string)
- func (r *Router) NotFound(handlers ...Handler)
- func (r *Router) Route(name string) *Route
- func (r *Router) Routes() []*Route
- func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)
- func (r *Router) Use(handlers ...Handler)
- type XMLDataReader
Examples ¶
Constants ¶
const ( MIME_JSON = "application/json" MIME_XML = "application/xml" MIME_XML2 = "text/xml" MIME_HTML = "text/html" MIME_FORM = "application/x-www-form-urlencoded" MIME_MULTIPART_FORM = "multipart/form-data" )
MIME types used when doing request data reading and response data writing.
Variables ¶
var Methods = []string{
"CONNECT",
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT",
"TRACE",
}
Methods lists all supported HTTP methods by Router.
Functions ¶
func MethodNotAllowedHandler ¶
MethodNotAllowedHandler handles the situation when a request has matching route without matching HTTP method. In this case, the handler will respond with an Allow HTTP header listing the allowed HTTP methods. Otherwise, the handler will do nothing and let the next handler (usually a NotFoundHandler) to handle the problem.
func NotFoundHandler ¶
NotFoundHandler returns a 404 HTTP error indicating a request has no matching route.
func ReadFormData ¶
ReadFormData populates the data variable with the data from the given form values.
Types ¶
type Context ¶
type Context struct {
Request *http.Request // the current request
Response http.ResponseWriter // the response writer
// contains filtered or unexported fields
}
Context represents the contextual data and environment while processing an incoming HTTP request.
func NewContext ¶
NewContext creates a new Context object with the given response, request, and the handlers. This method is primarily provided for writing unit tests for handlers.
func (*Context) Abort ¶
func (c *Context) Abort()
Abort skips the rest of the handlers associated with the current route. Abort is normally used when a handler handles the request normally and wants to skip the rest of the handlers. If a handler wants to indicate an error condition, it should simply return the error without calling Abort.
func (*Context) Form ¶
Form returns the first value for the named component of the query. Form reads the value from POST and PUT body parameters as well as URL query parameters. The form takes precedence over the latter. If key is not present, it returns the specified default value or an empty string.
func (*Context) Get ¶
Get returns the named data item previously registered with the context by calling Set. If the named data item cannot be found, nil will be returned.
func (*Context) Next ¶
Next calls the rest of the handlers associated with the current route. If any of these handlers returns an error, Next will return the error and skip the following handlers. Next is normally used when a handler needs to do some postprocessing after the rest of the handlers are executed.
func (*Context) Param ¶
Param returns the named parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, an empty string will be returned.
func (*Context) PostForm ¶
PostForm returns the first value for the named component from POST and PUT body parameters. If key is not present, it returns the specified default value or an empty string.
func (*Context) Query ¶
Query returns the first value for the named component of the URL query parameters. If key is not present, it returns the specified default value or an empty string.
func (*Context) Read ¶
Read populates the given struct variable with the data from the current request. If the request is NOT a GET request, it will check the "Content-Type" header and find a matching reader from DataReaders to read the request data. If there is no match or if the request is a GET request, it will use DefaultFormDataReader to read the request data.
func (*Context) Set ¶
Set stores the named data item in the context so that it can be retrieved later.
func (*Context) SetDataWriter ¶
func (c *Context) SetDataWriter(writer DataWriter)
SetDataWriter sets the data writer that will be used by Write().
func (*Context) SetParam ¶
SetParam sets the named parameter value. This method is primarily provided for writing unit tests.
func (*Context) URL ¶
URL creates a URL using the named route and the parameter values. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. Parameter values will be properly URL encoded. The method returns an empty string if the URL creation fails.
type DataReader ¶
type DataReader interface {
// Read reads from the given HTTP request and populate the specified data.
Read(*http.Request, interface{}) error
}
DataReader is used by Context.Read() to read data from an HTTP request.
var ( // DataReaders lists all supported content types and the corresponding data readers. // Context.Read() will choose a matching reader from this list according to the "Content-Type" // header from the current request. // You may modify this variable to add new supported content types. DataReaders = map[string]DataReader{ MIME_FORM: &FormDataReader{}, MIME_MULTIPART_FORM: &FormDataReader{}, MIME_JSON: &JSONDataReader{}, MIME_XML: &XMLDataReader{}, MIME_XML2: &XMLDataReader{}, } // DefaultFormDataReader is the reader used when there is no matching reader in DataReaders // or if the current request is a GET request. DefaultFormDataReader DataReader = &FormDataReader{} )
type DataWriter ¶
type DataWriter interface {
// SetHeader sets necessary response headers.
SetHeader(http.ResponseWriter)
// Write writes the given data into the response.
Write(http.ResponseWriter, interface{}) error
}
DataWriter is used by Context.Write() to write arbitrary data into an HTTP response.
var DefaultDataWriter DataWriter = &dataWriter{}
DefaultDataWriter writes the given data in an HTTP response. If the data is neither string nor byte array, it will use fmt.Fprint() to write it into the response.
type FormDataReader ¶
type FormDataReader struct{}
FormDataReader reads the query parameters and request body as form data.
type HTTPError ¶
type HTTPError interface {
error
// StatusCode returns the HTTP status code of the error
StatusCode() int
}
HTTPError represents an HTTP error with HTTP status code and error message
func NewHTTPError ¶
NewHTTPError creates a new HttpError instance. If the error message is not given, http.StatusText() will be called to generate the message based on the status code.
type Handler ¶
Handler is the function for handling HTTP requests.
func HTTPHandler ¶
HTTPHandler adapts a http.Handler into a routing.Handler.
func HTTPHandlerFunc ¶
func HTTPHandlerFunc(h http.HandlerFunc) Handler
HTTPHandlerFunc adapts a http.HandlerFunc into a routing.Handler.
type JSONDataReader ¶
type JSONDataReader struct{}
JSONDataReader reads the request body as JSON-formatted data.
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route represents a URL path pattern that can be used to match requested URLs.
func (*Route) Name ¶
Name sets the name of the route. This method will update the registration of the route in the router as well.
func (*Route) Tags ¶
func (r *Route) Tags() []interface{}
Tags returns all custom data associated with the route.
func (*Route) To ¶
To adds the route to the router with the given HTTP methods and handlers. Multiple HTTP methods should be separated by commas (without any surrounding spaces).
func (*Route) URL ¶
URL creates a URL using the current route and the given parameters. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. The method will perform URL encoding for all given parameter values.
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup represents a group of routes that share the same path prefix.
func (*RouteGroup) Any ¶
func (rg *RouteGroup) Any(path string, handlers ...Handler) *Route
Any adds a route with the given route, handlers, and the HTTP methods as listed in routing.Methods.
func (*RouteGroup) Connect ¶
func (rg *RouteGroup) Connect(path string, handlers ...Handler) *Route
Connect adds a CONNECT route to the router with the given route path and handlers.
func (*RouteGroup) Delete ¶
func (rg *RouteGroup) Delete(path string, handlers ...Handler) *Route
Delete adds a DELETE route to the router with the given route path and handlers.
