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 PathParameter ¶ added in v0.2.0
PathParameter returns the nth path parameter from the request context. It returns an empty string if no value exists at the given index.
Example ¶
mux := new(ServeMux) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() fmt.Fprintln(w, PathParameter(ctx, 0)) fmt.Fprintln(w, PathParameter(ctx, 1)) }) 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 corresponding to // the request URL. If NotFoundHandler is nil, http.NotFoundHandler // will be used. NotFoundHandler http.Handler // MethodNotAllowedHandler is called when there is no method corresponding // 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.