Gorilla Mux URL matching

Here’s my testing code:


import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	multiplex := mux.NewRouter()
	multiplex.HandleFunc("/", WelcomeHandler)
	multiplex.HandleFunc("/directory/", DirectoryHandler)
	multiplex.HandleFunc("/dashboard/{userId}/", DashboardHandler)

	http.ListenAndServe("127.0.0.1:8000", multiplex)
}

// WelcomeHandler Handles requests for welcome Page
func WelcomeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<h1>Welcome Page!</h1>")
}

// DirectoryHandler Handles requests for directory
func DirectoryHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<h1>Directory Page!</h1>")
}

// DashboardHandler Handles requests for dashboard
func DashboardHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<h1>Dashboard!</h1>")
}

I’m curious why it is that if I go to the /dashboard/{anything other than exactly userId}/ that it 404’s by default. I assumed it was going to do something to auto parse the url for data retrieval, but I appear to have been wrong.

I got a 200 that displayed “Dashboard!” when accessing http://127.0.0.1:8000/dashboard/hello/

My guess is the urls you tried were missing the final /, which was required by pattern designated.

2 Likes

See http://www.gorillatoolkit.org/pkg/mux#Router.StrictSlash if you want to alter that behavior. Iirc the true/false settings are opposite of what I expected.

1 Like

I must’ve done something like that, because it’s working for me now as well.

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