Documentation
¶
Overview ¶
This package replaces the standard muxer provided by the standard library with a more flexible method of specifying URLs.
In the package net/http, the function ListenAndServe accepts a normal request handler. This interface is called to create content for requests that the server receives. Typically, a special handler is used to multiplex requests. The request multiplexer matches the URL of incoming requests against a list of registered handlers, and then dispatches that request as required.
The multiplexer provided by the standard Go library matches requests by the URLs' prefixes. This is a simple approach, but does not necessarily provide as much functionality as desired.
This package provides another method of mutliplexing request. A list of regular expressions is registered with a builder. When desired, this list is compiled into a finite state machine that can match requests to a specific target. In additional to providing more flexibility in routing requests, the regular expressions can verify the format of the URLs. Malformed requests return a 404 error.
Index ¶
Examples ¶
Constants ¶
const ( GetMethod = Method(1 << iota) PostMethod PutMethod DeleteMethod AllMethods Method = GetMethod | PostMethod | PutMethod | DeleteMethod )
Variables ¶
var (
ErrBuilderIsEmpty = errors.New("Can not create ServeMux. The Builder is empty.")
)
Functions ¶
func PathNth ¶
PathNth returns the nth element of the path. If the element is found, it is returned without the leading or trailing slashes.
The first element has an index of zero. If the path has a leading slash, it is ignored. Therefore, the leading elements (element 0) of "/a/b/c" and "a/b/c" are both "a".
The last element in the path may contain a trailing slash, but it is not required. For example, the final elements (element 2) of "/a/b/c/" and "/a/b/c" are both "c".
Example ¶
// An example path in a request path := "/diary/user/2012-12-25/1" // breakout the elements username := PathNth(path, 1) entrydate := PathNth(path, 2) entryindex := PathNth(path, 3) // show the results fmt.Println("User:", username) fmt.Println("Entry date:", entrydate) fmt.Println("Entry index:", entryindex)
Output: User: user Entry date: 2012-12-25 Entry index: 1
func UrlNth ¶
UrlNth returns the nth element of the URL's path. Refer to PathNth for more details.
Example ¶
// An example path in a request url, err := url.Parse("http://localhost/diary/user/2012-12-25/1") if err != nil { panic(err) } // breakout the elements username := UrlNth(url, 1) entrydate := UrlNth(url, 2) entryindex := UrlNth(url, 3) // show the results fmt.Println("User:", username) fmt.Println("Entry date:", entrydate) fmt.Println("Entry index:", entryindex)
Output: User: user Entry date: 2012-12-25 Entry index: 1
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
A Builder maintains a list of regular expressions, and the HTTP handlers that should be executed when that expression matches the URL of an HTTP request.
func NewBuilder ¶
func NewBuilder() *Builder
NewBuilder initializes a new Builder.
Example ¶
// Create a builder to start construction of our routing policy b := NewBuilder() // The login page will be special. A get method will return an HTML // login page, but we'll post our credentials to login b.HandleFunc("/login", GetMethod, func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<html><body>A login page.</body></html>") }) b.HandleFunc("/login", PostMethod, func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<html><body>You're logged in!</body></html>") }) // Our content will be organized by date, which will be part // of our URL. b.HandleFunc("/content/\\d{4}-\\d{2}-\\d{2}/?", GetMethod, func(w http.ResponseWriter, r *http.Request) { date := r.URL.Path[9:19] // A string of the form YYYY-MM-DD fmt.Fprintf(w, "<html><body>Some content for %s.</body></html>", date) }) // Construct a ServerMux. This will construct the DFA based on the // requested patterns that can be used for routing. mux, err := b.NewServeMux() if err != nil { // If you have conflicting routes, you will find out here panic(err) } // Start serving content. go http.ListenAndServe(":8000", mux) time.Sleep(1 * time.Second)
Output:
func (*Builder) Handle ¶
Handle registers the handler for the given method and given regular expression. If the regular expression already exists, the handlers for those methods specified by the parameter method are overwritten.
The pattern is a regular expression conforming to the syntax of the package regexp. The expression must be valid. If it fails to compile, this method will panic.
func (*Builder) HandleFunc ¶
func (n *Builder) HandleFunc(pattern string, method Method, handler func(http.ResponseWriter, *http.Request))
HandleFunc registers the handler function for the given method and the given regular expression. See the method Handle.
func (*Builder) NewServeMux ¶
NewServeMux compiles the list of regular expressions into a machine, and returns a new request multiplexer that will dispatch HTTP requests.
type ErrAcceptConflict ¶
type ErrAcceptConflict struct {
// contains filtered or unexported fields
}
An ErrAcceptConflict will be returned when building the state machine if it is possible for an URL to match multiple handlers. The regular expressions must match distinct sets of string.�
func (ErrAcceptConflict) Error ¶
func (e ErrAcceptConflict) Error() string
type ErrorHandler ¶
type ErrorHandler struct {
// contains filtered or unexported fields
}
A ErrorHandler writes an error message to the HTTP response with the error code and the associated error text. Users should initialize the structure with a standard HTTP error code.
func (*ErrorHandler) ServeHTTP ¶
func (h *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP write reply headers for the error code, and creates a short response with text that describes the error.
type Method ¶
type Method int
A Method specifies the method for an HTTP request. Note that when used to specify the methods for a handler, the values can be combined.
type ServeMux ¶
type ServeMux struct { // NotFoundHandler is called to write error messages for 404 code // errors. NotFoundHandler http.Handler // MethodNotAllowedHandler is called to write error messages for 405 // code errors. MethodNotAllowedHandler http.Handler // contains filtered or unexported fields }
A ServeMux is a request multiplexer. Incoming HTTP requests are matches against a list of regular expressions, and the request is dispatched to the appropriate handler.
The multiplexer contains two special handler for handling errors. These are otherwise normal handlers, but users should not that the HTTP headers have already been sent when they are called.