Hi I am working on a golang project. 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!
Try the following:
const feedbackPath = "/products/feedback/" // note trailing slash.
func AddFeedbackHandler(w http.ResponseWriter, r *http.Request) {
var slug string
if strings.HasPrefix(r.URL.Path, feedbackPath) {
slug = r.URL.Path[len(feedbackPath):]
}
fmt.Println("the slug is: ", slug)
w.Write([]byte("ChecksOut"))
}
Add the handler with this code:
http.HandleFunc(feedbackPath, AddFeedbackHandler)
The trailing slash on the path is required for a subtree match. You can read the details on the use of the trailing slash in the ServeMux documentation.