Go’s standard-library `net/http` package provides HTTP clients and servers. Use its helpers for a simple request or server, then work with requests, clients, and handlers when you need more control. section 1.2.2 section 11.1.1
Serve a response
Register a function for `/`, then listen on localhost: ```go package main import ( "fmt" "log" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, world") } func main() { http.HandleFunc("/", hello) log.Fatal(http.ListenAndServe("localhost:4000", nil)) } ``` Run it with `go run main.go` and visit `http://localhost:4000`. The handler receives the request and writes the response through `http.ResponseWriter`. section 1.5 section 1.2.2
Retrieve a response body
For a straightforward GET, call `http.Get`, check the error, and close the response body when finished: ```go package main import ( "io" "log" "net/http" ) func main() { resp, err := http.Get("http://example.com/") if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } log.Println(string(body)) } ``` section 1.2.2
`http.Get`, `http.Head`, `http.Post`, and `http.PostForm` cover common client calls. For another method, create an `http.Request` and pass it to a client’s `Do` method. A custom `http.Client` can set a timeout; client configuration can also control redirects, cookies, and the transport layer. section 11.1.1
Listing 11.2 DELETE request with default HTTP client
package main
import (
"fmt"
"net/http"
)
func main() {
req, err := http.NewRequest("DELETE",
"http://example.com/foo/bar", nil) #1
if err != nil {
panic(err)
}
res, err := http.DefaultClient.Do(req) #2
if err != nil {
panic(err)
}
fmt.Printf("%s", res.Status) #3
}
A DELETE request shows how to separate request construction from execution with `http.DefaultClient.Do`. section 11.1.1
Listing 11.3 A simple custom HTTP client
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func main() {
cc := &http.Client{Timeout: time.Second} #1
res, err := cc.Get("http://www.manning.com") #2
if err != nil { #3
panic(err)
}
b, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
defer res.Body.Close()
fmt.Printf("%s", b)
}
A custom client sets a one-second timeout before making a GET request. section 11.1.1
For larger servers, routing and middleware help select handlers and share common work. The package also supplies functionality for form submissions and multipart POST or PUT requests. These building blocks can be extended for real-world applications without starting with a third-party framework. section 8.0 section 10.2


