How to Handle Routes in Go: Simple Guide with Examples
net/http package's http.HandleFunc or by using third-party routers like gorilla/mux for more complex routing. Define handler functions for each route and register them with the router to respond to HTTP requests.Why This Happens
Beginners often try to handle routes in Go by writing multiple http.HandleFunc calls but forget to start the server properly or mix route patterns incorrectly. This causes the server to not respond as expected or return 404 errors.
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Welcome Home") }) http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "About Us") }) // Forgot to start the server // http.ListenAndServe(":8080", nil) }
The Fix
You must start the HTTP server with http.ListenAndServe and pass the default router (nil) or a custom router. For more complex routing, use gorilla/mux which allows variables and methods in routes.
package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Welcome Home") }).Methods("GET") r.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "About Us") }).Methods("GET") http.ListenAndServe(":8080", r) }
Prevention
Always start your HTTP server with http.ListenAndServe and pass the correct router. Use third-party routers like gorilla/mux for better route management, especially when you need variables or HTTP method handling. Test routes early and use tools like curl or browser to verify responses.
Related Errors
Common related errors include 404 Not Found due to missing routes, 405 Method Not Allowed when HTTP methods are not handled, and server crashes from missing ListenAndServe. Fix these by ensuring routes are registered correctly and the server is started.