Go > Web Development > HTTP Basics > net/http package overview

Handling Multiple Routes with net/http

This snippet expands on the previous example by demonstrating how to handle multiple routes in a Go web server using the net/http package. It shows how to register different handler functions for different URL paths, providing a more structured approach to web application development.

Code Example: Multiple Routes

This code defines two handler functions: homeHandler for the root path ('/') and aboutHandler for the '/about' path. Each handler writes a different message to the response. The http.HandleFunc function is used to register each handler with its corresponding path. The http.ListenAndServe function then starts the server, listening for incoming connections and dispatching requests to the appropriate handlers based on the URL path.

package main

import (
	"fmt"
	"net/http"
	"log"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the Home Page!\n")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This is the About Page.\n")
}

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)

	fmt.Println("Server listening on port 8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Concepts Behind the Snippet

This snippet highlights the following key concepts:

  • Route Definition: Using http.HandleFunc to associate specific URL paths with corresponding handler functions.
  • Request Dispatching: The net/http package automatically dispatches incoming requests to the appropriate handler based on the requested URL path.
  • Modular Design: Separating the handling of different routes into distinct functions promotes code organization and maintainability.

Real-Life Use Case

This pattern is commonly used in web applications to handle different functionalities based on the URL path. For example, you might have separate routes for displaying a home page, handling user authentication, and processing form submissions.

Best Practices

  • Consistent Naming: Use consistent naming conventions for handler functions and URL paths to improve code readability.
  • Route Organization: Organize your routes logically to make it easier to maintain and extend your web application.
  • Middleware: Consider using middleware to handle common tasks such as authentication, logging, and request validation.

Interview Tip

Be prepared to discuss how routing works in Go's net/http package, the trade-offs of using the built-in router versus external routers and how to manage complex routing scenarios.

When to use them

Use this pattern when you need to handle multiple distinct functionalities or resources in your web application, each accessible through a different URL.

Alternatives

For more complex routing requirements, consider using external router libraries such as Gin, Echo, or Chi, which offer features like route parameters, middleware support, and more advanced routing patterns.

Pros

  • Simple and built-in
  • Easy to learn and use for basic routing
  • No external dependencies for simple cases

Cons

  • Limited features compared to external routers
  • Can become difficult to manage for complex routing patterns
  • Lacks middleware support in its basic form

FAQ

  • How does http.HandleFunc determine which handler to call?

    http.HandleFunc registers a handler function with the DefaultServeMux. When a request comes in, the DefaultServeMux compares the request's URL path against the registered paths and calls the handler associated with the most specific matching path.
  • Can I use regular expressions in my routes?

    The built-in net/http router does not directly support regular expressions in routes. For regular expression routing, you'll need to use an external router library.
  • How can I handle 404 errors (Not Found)?

    You can define a default handler that is called when no other route matches. This handler can then return a 404 error using http.NotFound(w, r).