Golang http.HandleFunc not working with slugs

When I try to use slugs with http.HandleFunc I get a “404 page not found error”. When I take the slug out my routing works again.

In main I have:

http.HandleFunc("/products/feedback/{slug}", AddFeedbackHandler)

Which calls:

var AddFeedbackHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
w.Write([]byte(“ChecksOut”))
})

When I replace the path with:

http.HandleFunc("/products/feedback", AddFeedbackHandler)

It works again. What might be causing this? Please forgive me if this is a basic question, I am new to golang and still trying to get the hang of it. Thanks!

Hey @thegrinch,

If you are actually trying to use the slug in your handler, then I have a feeling you are trying to set up your routes as if you were working with gorilla/mux which allows slugs to be used as variables passed to your function, so if that’s the case, then have a look at http://www.gorillatoolkit.org/pkg/mux.

The way you have it in the first snippet, AddFeedbackHandler will only be called if the URL path is an exact match for the string /products/feedback/{slug}. http.ServeMux does not support variables in the path; were you expecting {slug} to be treated as a variable?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.