Skip to content

net/http: add example for ServeMux to make "/.*" behavior clear #4799

Closed
@shields

Description

@shields
As discussed on golang-nuts:

I expected this code to serve pages at http://localhost:8080/ and
http://localhost:8080/foo, with 404s for any other path.

        http.HandleFunc("/", indexHandler)
        http.HandleFunc("/foo", fooHandler)
        log.Fatal(http.ListenAndServe(":8080", nil))

Surprisingly, /bar is also valid.  It gets indexHandler, because as "/subdir/"
includes an entire subtree, "/" includes the entire tree. This means that
indexHandler must test req.URL.Path == "/" and explicitly 404 any other paths.

Being able to serve all endpoints easily is useful, but I think in many cases people are
doing it unintentionally, i.e., writing bugs.

This is only surprising for "/", since the documentation is clear about how
"/foo/" works.

Possible resolutions:


1. I suggested allowing "" to match the root path only.  "" is
currently an invalid pattern, so this is a backwards-compatible change.


2. adg suggested a wrapper:

        func ExactPath(path string, http.Handler) http.Handler

Using this involves some stutter:

        mux.Handle("/", http.ExactPath("/", h))

This seems more general in that you could also use it for non-index paths such as
"/a/b/", but there would still be a questionable redirect from
"/a/b".



3. Remove the stutter and generality:

        mux.Handle("/", http.IndexOnly(indexHandler))


4. Exact registration, which would work for non-index paths:

        mux.HandleExact("/", indexHandler)


5. We could just warn people to check req.URL.Path in their index handlers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions