Job van Esch
Job van Esch

Reputation: 19

Golang handlefunc

So I have this weird issue where some routes will work and others won't. I will first show you my main function and then give examples of what the problem is.

func main() {
    http.HandleFunc("/", home)
    http.HandleFunc("/project", project)
    http.HandleFunc("/about", about)
    http.HandleFunc("/contact", contact)

    http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("./assets"))))

    err := http.ListenAndServe(":80", nil)
    if err != nil {
        fmt.Println("ListendAndServe doesn't work : ", err)
    }
}

For example, the route "/contact/" does not work, when I run this code and go to localhost/contact it will send me to the homepage. However when I change the route in the Handlefunc to "/contactos" and then go to localhost/contactos it does work.

Another example, "/project" works now, but when I change it to "/projects" it does not.

Upvotes: 1

Views: 1759

Answers (1)

icza
icza

Reputation: 418675

Note that if you register /project/ (note the trailing slash), then both /project/ and /project will work (with or without trailing slash). If you register /project (without a trailing slash), then only /project will work, /project/ will be matched by the root handler /.

Quoting from http.ServeMux:

If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.

See related questions:

How to map to the same function with a pattern that ends with or with "/" with http.HandleFunc

Upvotes: 3

Related Questions