Documentation
¶
Overview ¶
Package apirouter provides a lightning fast RESTful api router.
A trivial example is:
package main
import (
"fmt"
"github.com/cnotch/apirouter"
"net/http"
"log"
)
func Index(w http.ResponseWriter, r *http.Request, _ apirouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Hello(w http.ResponseWriter, r *http.Request, ps apirouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := apirouter.New(
apirouter.GET("/", Index),
apirouter.GET("/hello/:name", Hello),
)
log.Fatal(http.ListenAndServe(":8080", router))
}
The registered pattern, against which the router matches incoming requests, can contain three types of parameters(default style):
Syntax Type :name named parameter :name=regular-expressions regular expression parameter *name wildcard parameter
Matching priority, on the example below the router will test the routes in the following order, /users/list then /users/:id=^\d+$ then /users/:id then /users/*page.
r:= apirouter.New(
apirouter.GET("/users/:id",...),
apirouter.GET(`/users/:id=^\d+$`,...),
apirouter.GET("/users/*page",...),
apirouter.GET("/users/list",...),
)
Named parameters are dynamic path segments. They match anything until the next '/' or the path end:
Pattern: /blog/:category/:post Requests: /blog/go/request-routers match: category="go", post="request-routers" /blog/go/request-routers/ no match /blog/go/ no match /blog/go/request-routers/comments no match
If a parameter must match an exact pattern (digits only, for example), you can also set a regular expression constraint just after the parameter name and `=`.
Pattern: /users/:id=^\d+$ Requests: /users/123 match: id="123" /users/admin no match /users/123/ no match
Wildcard parameters match anything until the path end, not including the directory index (the '/' before the '*'). Since they match anything until the end, wildcard parameters must always be the final path element.
Path: /files/*filepath Requests: /files/ match: filepath="" /files/LICENSE match: filepath="LICENSE" /files/templates/article.html match: filepath="templates/article.html" /files no match
The value of parameters is saved as a Params. The Params is passed to the Handler func as a third parameter. If the handler is registered with Handle or HandleFunc, params is stored in request's context.
Example:
r:=apirouter.New(
apirouter.GET("/streams/:id", func(w http.ResponseWriter, r *http.Request, ps apirouter.Params) {
id := ps.ByName("id")
fmt.Fprintf(w, "Page of stream #%s", id)
}),
apirouter.HandleFunc("GET","/users/:id", func(w http.ResponseWriter, r *http.Request) {
ps := apirouter.PathParams(r.Context())
id := ps.ByName("id")
fmt.Fprintf(w, "Page of user #%s", id)
}),
)
Index ¶
- func WrapHandler(h http.Handler, interceptors ...Interceptor) http.Handler
- func WrapHandlerFunc(h http.HandlerFunc, interceptors ...Interceptor) http.HandlerFunc
- type Handler
- type Interceptor
- type Option
- func API(method string, pattern string, handler Handler) Option
- func DELETE(pattern string, handler Handler) Option
- func GET(pattern string, handler Handler) Option
- func HEAD(pattern string, handler Handler) Option
- func Handle(method string, pattern string, handler http.Handler) Option
- func HandleFunc(method string, pattern string, ...) Option
- func NotFoundHandler(handler http.Handler) Option
- func OPTIONS(pattern string, handler Handler) Option
- func PATCH(pattern string, handler Handler) Option
- func POST(pattern string, handler Handler) Option
- func PUT(pattern string, handler Handler) Option
- type Params
- type Pattern
- type PostInterceptor
- type PreInterceptor
- type Router
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WrapHandler ¶
func WrapHandler(h http.Handler, interceptors ...Interceptor) http.Handler
WrapHandler wraps the http.Handler with the interceptors and transforms it into a different http.Handler
func WrapHandlerFunc ¶
func WrapHandlerFunc(h http.HandlerFunc, interceptors ...Interceptor) http.HandlerFunc
WrapHandlerFunc wraps the http.HandlerFunc with the interceptors and transforms it into a different http.HandlerFunc
Types ¶
type Handler ¶
type Handler func(w http.ResponseWriter, r *http.Request, ps Params)
Handler is a function that can be registered to a router to handle HTTP requests.
Compared with http.HandlerFunc, it add the third parameter for the path parameters extracted from the HTTP request.
func Wrap ¶
func Wrap(h Handler, interceptors ...Interceptor) Handler
Wrap wraps the hanndler with the interceptors and transforms it into a different handler
type Interceptor ¶
type Interceptor interface {
// PreHandle achieve the preprocessing of the HTTP request handler (such as check login).
// return value:
// true - continue the process (such as calling the next interceptor or Handler);
// false - interrupte the process(such as the logon check fails)
// and will not continue to invoke other interceptors or Handler,
// in which case we need to generate a response through w.
PreHandle(w http.ResponseWriter, r *http.Request) bool
// PostHandle achieve the post-processing of the HTTP request handler.
PostHandle(r *http.Request)
}
Interceptor provides a hook to intercept the execution of the HTTP request handler.
func ChainInterceptor ¶
func ChainInterceptor(its ...Interceptor) Interceptor
ChainInterceptor creates a single interceptor out of a chain of many interceptors.
PreHandle's Execution is done in left-to-right order. For example ChainInterceptor(one, two, three) will execute one before two before three, and three will see r changes of one and two. PostHandle's Execution is done in right-to-left order.
func NewInterceptor ¶
func NewInterceptor(pre PreInterceptor, post PostInterceptor) Interceptor
NewInterceptor returns a new Interceptor.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option represents all possible options to the New() function
func API ¶
API creates the option to registers api.
- method: supported HTTP methods,
- pattern: url path matched pattern,
- handler: http request handler.
func Handle ¶
Handle creates the option to perform similar actions with the standard library http.Handle.
func HandleFunc ¶
func HandleFunc(method string, pattern string, handler func(http.ResponseWriter, *http.Request)) Option
HandleFunc creates the option to perform similar actions with the standard library http.HandleFunc.
func NotFoundHandler ¶
NotFoundHandler creates the option to set a request handler that replies to each request with a “404 page not found” reply.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params holds the path parameters extracted from the HTTP request.
func PathParams ¶
PathParams pulls the path parameters from a request context, or returns nil if none are present.
func (Params) ByName ¶
ByName returns the value of the first parameter that matched the given name. Otherwise, an empty string is returned.
type Pattern ¶
type Pattern struct {
// contains filtered or unexported fields
}
Pattern a parsed representation of path pattern. eg github.com/googleapis/googleapis/google/api/http.proto.
func MustPattern ¶
MustPattern is a helper function which makes it easier to call NewPattern or NewGRPCPattern in variable initialization.
func NewGRPCPattern ¶
NewGRPCPattern creates a gRPC style's new Pattern from the given original pattern. "regexps" is a list of regular expressions shared between multiple patterns.
The syntax of the pattern string is as follows:
Pattern = "/" Segments [ Verb ]
Segments = Segment { "/" Segment }
Segment = LITERAL | Parameter
Parameter = Anonymous | Named
Anonymous = "*" | "**"
Named = "{" FieldPath [ "=" Wildcard ] "}"
Wildcard = "*" | "**" | Regexp
FieldPath = IDENT { "." IDENT }
Verb = ":" LITERAL
func NewPattern ¶
NewPattern creates a default style's new Pattern from the given original pattern. "regexps" is a list of regular expressions shared between multiple patterns.
The syntax of the pattern string is as follows:
Pattern = "/" Segments
Segments = Segment { "/" Segment }
Segment = LITERAL | Parameter
Parameter = Anonymous | Named
Anonymous = ":" | "*"
Named = ":" FieldPath [ "=" Regexp ] | "*" FieldPath
FieldPath = IDENT { "." IDENT }
type PostInterceptor ¶
PostInterceptor provides a hook function to intercept after the HTTP request handler is executed.
func (PostInterceptor) PostHandle ¶
func (f PostInterceptor) PostHandle(r *http.Request)
PostHandle implements Intercetor.PostHandle.
func (PostInterceptor) PreHandle ¶
func (f PostInterceptor) PreHandle(w http.ResponseWriter, r *http.Request) bool
PreHandle implements Intercetor.PreHandle with no-op. It always returns true.
type PreInterceptor ¶
type PreInterceptor func(w http.ResponseWriter, r *http.Request) bool
PreInterceptor provides a hook function to intercept before the HTTP request handler is executed.
func (PreInterceptor) PostHandle ¶
func (f PreInterceptor) PostHandle(r *http.Request)
PostHandle implements Intercetor.PostHandle with no-op.
func (PreInterceptor) PreHandle ¶
func (f PreInterceptor) PreHandle(w http.ResponseWriter, r *http.Request) bool
PreHandle implements Intercetor.PreHandle.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router implements http.Handler interface. It matches the URL of each incoming request, and calls the handler that most closely matches the URL.
NOTES: The zero value for Route is not available, it must be created with call New() function.
func New ¶
New returns a new Router,which is initialized with the given options and default pattern style.
The syntax of the pattern reference apirouter.NewPattern.
func NewForGRPC ¶
NewForGRPC returns a new Router,which is initialized with the given options and gRPC pattern style.
The syntax of the pattern reference apirouter.NewGRPCPattern.