Handle routes in Go by mapping URL patterns to functions using http.HandleFunc and starting the server with http.ListenAndServe.
Use http.HandleFunc to map URL patterns to handler functions, then call http.ListenAndServe to start the server.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s", r.URL.Path)
})
http.ListenAndServe(":8080", nil)
}
Handling routes in Go with net/http sets up a basic web server that listens for incoming requests on a specific port. When a request arrives, the server checks the URL path and runs the matching function you defined to generate a response. It is like a receptionist who directs callers to the right department based on the number they dialed.