Go net/http Package: Building Web Servers and Clients
Learn Go through interactive, bite-sized lessons. Build scalable applications with modern concurrency.
Start Go Journey →The net/http package is a powerful and versatile component of Go's standard library. It provides a robust set of tools for creating HTTP clients and servers, making it an essential package for web development in Go.
Key Features
- HTTP server creation
- Request handling and routing
- HTTP client functionality
- Support for HTTPS
- Cookie management
Creating an HTTP Server
One of the primary uses of the net/http package is to create HTTP servers. Here's a simple example:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
In this example, we define a handler function and use http.HandleFunc to associate it with the root path. The server listens on port 8080.
Making HTTP Requests
The net/http package also provides functionality for making HTTP requests. Here's how you can make a GET request:
resp, err := http.Get("https://api.example.com/data")
if err != nil {
// Handle error
}
defer resp.Body.Close()
// Read the response body
Request Routing
For more complex applications, you might want to use the http.ServeMux for request routing:
mux := http.NewServeMux()
mux.HandleFunc("/api/data", dataHandler)
mux.HandleFunc("/api/users", usersHandler)
http.ListenAndServe(":8080", mux)
Best Practices
- Always close response bodies to prevent resource leaks
- Use
http.Clientfor more control over requests - Implement proper error handling for robust applications
- Consider using third-party routers for complex routing needs
Related Concepts
To deepen your understanding of web development in Go, explore these related topics:
- Go Goroutines for concurrent request handling
- Go Context for request cancellation and timeouts
- Go encoding/json Package for working with JSON data
The net/http package is a cornerstone of web development in Go. By mastering its features, you'll be well-equipped to build efficient and scalable web applications.