http.HandleFunc and URL handlers

I’m building a simple REST API in Go and have a question.

I have a HandleFunc that looks like this:

    http.HandleFunc("/users", userHandler)

and that points to the user handler. What I want is another HandleFunc at /users that lets me load handlers for sub-URLs such as /users/login and /users/logout so that I don’t have hundreds of HandleFunc in my main() function.

I’m fairly new to Go so it is quite likely I am missing something obvious so if you could point me in the right direction I would appreciate it.

Hello there. There is probably a way you’d want to try, something like this:

mux.HandleFunc("GET /users/{path}", func(w http.ResponseWriter, r *http.Request) {
	switch r.PathValue("path") {
	case "login":
		w.WriteHeader(http.StatusOK)
		return
	case "logout":
		w.WriteHeader(http.StatusOK)
		return
	default:
		http.Error(w, "path is not defined", 404)
	}
})
1 Like

Thank you! That looks good.

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