liveBook · Manning

Net/http package

As explained in Go by Example

The http package is Go's standard-library package providing HTTP client and server implementations and related types.

The net/http package provides Go's standard-library HTTP clients, servers, requests, responses, handlers, and supporting types. It supports practical HTTP work without requiring an external framework. section 7.0 section 8.3

An HTTP client creates a Request, optionally attaches a context, sends it with Client.Do, checks the Response status, and reads Response.Body as a byte stream. Client.Transport maintains pooled TCP connections for efficiency. section 7.3 section 7.3.1

A server uses the complementary request-handling path:

  • Implement ServeHTTP on a type to satisfy the http.Handler interface. section 8.3
  • Register the handler on an http.Server, which invokes it concurrently for incoming requests. section 8.3
  • Use ResponseWriter to set headers, write the status code, and write the response body in that order. section 8.3

Sending a request

Create a GET request with http.NewRequest or http.NewRequestWithContext, send it through http.DefaultClient.Do, and test res.StatusCode against constants such as http.StatusOK before consuming the body. section 7.3.1 section 7.3.1

Figure 7.4 Sending a request to a server using an HTTP client and receiving a response. When we receive a response, we can read its body as a byte stream.
A diagram of a diagram

AI-generated content may be incorrect.

Trace the client-side round trip from an HTTP request to a response whose body is consumed as a byte stream. section 7.3.1

How Go by Example covers it

How deep it goes
Explains client round trips and server handlers through APIs, execution flow, connection pooling, and response-writing order.
Examples
Uses concurrent request pipelines, NewRequest, NewRequestWithContext, Client.Do, status checks, handlers, and ResponseWriter.
What it assumes
Assumes basic Go and concurrency knowledge while developing cancellation, streaming I/O, HTTP, and testing techniques through project work.
What you can do after
Build it from scratch by sending HTTP requests, consuming responses, registering handlers, and serving clients.
How it connects
Connects HTTP clients and servers with context, io, http.Handler, http.Server, Transport, RoundTripper, httptest, and concurrent pipelines.

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 by Example. The section links point to the parts of the book it draws on.