`net/http` - HTTP Client & Server Implementations
The net/http package provides HTTP client and server implementations. It's a foundational package for building web applications and interacting with HTTP services in Go.
Key Concepts
Client
The http.Client type is used to send HTTP requests. It provides control over aspects like timeouts, redirects, and connection pooling.
Example: Making a GET Request
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
resp, err := http.Get("https://example.com")
if err != nil {
fmt.Printf("Error making GET request: %v\n", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return
}
fmt.Printf("Status Code: %d\n", resp.StatusCode)
fmt.Printf("Response Body: %s\n", body)
}
Server
The http.Server type allows you to build and run your own HTTP servers. You define request handlers to process incoming requests.
Example: Simple HTTP Server
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path)
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server starting on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Server error: %v\n", err)
}
}
Request and Response
The http.Request and http.Response types represent the messages exchanged between client and server. They contain crucial information like headers, body, method, and status code.
http.Request Fields
Method: The HTTP method (GET, POST, etc.).URL: The requested URL.Header: Request headers.Body: The request body.RemoteAddr: The remote address that sent the request.
http.Response Fields
StatusCode: The HTTP status code (200 OK, 404 Not Found, etc.).Status: The HTTP status text.Header: Response headers.Body: The response body.Request: The request that triggered this response.
Handlers
An http.Handler is an interface that defines a way to serve HTTP requests. The most common implementation is using functions via http.HandleFunc, which registers a function to a specific URL path.
Common Usage Patterns
- Fetching data from external APIs.
- Building RESTful web services.
- Creating static file servers.
- Proxying requests.
For more detailed information, explore the links in the sidebar.