net/http
Package http
The http
package implements a client and server for the HTTP protocol.
It provides convenient interfaces for common HTTP tasks, allowing developers to easily
send HTTP requests, handle responses, and build web servers.
net/http
Overview
The net/http
package is a cornerstone of Go's networking capabilities.
It offers a high-level API that abstracts away much of the complexity of HTTP,
while still providing access to lower-level details when needed.
Key features include:
- Client: Easily send GET, POST, and other HTTP requests.
- Server: Build robust and performant HTTP servers with routing and middleware support.
- Request/Response Handling: Process incoming requests and construct outgoing responses.
- URL Parsing: Utilities for parsing and manipulating URLs.
- TLS/SSL Support: Secure communication via HTTPS.
Getting Started
To send a simple HTTP GET request:
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
resp, err := http.Get("https://golang.org/")
if err != nil {
fmt.Printf("Error making 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 (first 100 chars): %s\n", string(body)[:100])
}
To start a simple HTTP server:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("Server starting on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Server error: %v\n", err)
}
}
Core Components
http.Client
: Manages HTTP requests.http.Server
: An HTTP server.http.Request
: Represents an HTTP request.http.Response
: Represents an HTTP response.http.Handler
: An interface for handling HTTP requests.http.HandleFunc
: Registers a function to handle a specific URL pattern.