Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MethodNotAllowedHandler ¶
MethodNotAllowedHandler returns a simple request handler that replies to each request with a "405 method not allowed" reply and writes the 405 status code.
func PathParameters ¶
PathParameters returns all the path parameters that were set when ServeHTTP was called on a request.
Example ¶
mux := new(ServeMux)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathParameters := PathParameters(r.Context())
fmt.Println(pathParameters)
})
mux.Handle("/foo/*/bar/*", http.MethodGet, handler)
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo/test/bar/92", nil)
mux.ServeHTTP(rw, req)
fmt.Println(rw.Body.String())
Output: [test 92]
Types ¶
type ServeMux ¶
type ServeMux struct {
// NotFoundHandler is called when there is no path corrosponding to
// the request URL. If NotFoundHandler is nil, http.NotFoundHandler
// will be used.
NotFoundHandler http.Handler
// MethodNotAllowedHandler is called when there is no method corrosponding
// to the request URL. If MethodNotAllowedHandler is nil, MethodNotAllowedHandler
// will be used.
MethodNotAllowedHandler http.Handler
// contains filtered or unexported fields
}
ServeMux is an HTTP request multiplexer. It matches the URL and method of the incoming request against a list of registered routes, and calls the matching route.
Example ¶
mux := new(ServeMux)
mux.Handle("/", http.MethodGet, stringHandler("health check"))
mux.Handle("/posts", http.MethodGet, stringHandler("create post"))
mux.Handle("/posts", http.MethodGet, stringHandler("get posts"))
mux.Handle("/posts/*", http.MethodGet, stringHandler("get post"))
mux.Handle("/posts/*/comments", http.MethodGet, stringHandler("get post comments"))
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
mux.ServeHTTP(rw, req)
fmt.Println(rw.Body.String())
rw = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/posts/4", nil)
mux.ServeHTTP(rw, req)
fmt.Println(rw.Body.String())
rw = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/posts/5/comments", nil)
mux.ServeHTTP(rw, req)
fmt.Println(rw.Body.String())
Output: health check get post get post comments
func (*ServeMux) Handle ¶
Handle registers a handler for the given pattern and method on the muxer. The pattern should be the exact URL to match, with the exception of wildcards ("*"), which can be used for a single segment of a path (split on "/") to match anything. A wildcard method of "*" can also be used to match any method.