0
0
GoDebug / FixBeginner · 4 min read

How to Handle Routes in Go: Simple Guide with Examples

In Go, you handle routes by using the 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.

go
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)
}
Output
panic: http: Server closed or no response when accessing routes
🔧

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.

go
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.

Key Takeaways

Always start your HTTP server with http.ListenAndServe and pass the router.
Use gorilla/mux for flexible and powerful route handling in Go.
Register each route with a handler function that writes a response.
Test your routes early to catch missing or misconfigured paths.
Handle HTTP methods explicitly to avoid 405 errors.