liveBook · Manning

Net/http package

As explained in Go in Practice, Second Edition

net/http is Go's standard library package for HTTP clients and servers.

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

How Go in Practice, Second Edition covers it

How deep it goes
Works through runnable GET and server examples, then describes request/client separation and configurable clients; server construction extends into routing and middleware.
Examples
Uses a localhost web server, a GET that reads a response body, a DELETE through the default client, and a timed custom client.
What it assumes
Assumes basic Go package, import, and main-function syntax while introducing handler registration and client calls through examples.
What you can do after
Build it from scratch as a small Go web server, and make GET or custom-client HTTP requests.
How it connects
Connects HTTP handlers to routing and middleware, and HTTP clients to requests, redirects, cookies, timeouts, and transports.

Also explained in

Compare how 3 books explain net/http package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.