liveBook · Manning

Http.NewRequest

As explained in Go by Example

httptest.NewRequest is a Go standard-library function that constructs an HTTP request for use in server tests and panics if its method or target is invalid.

http.NewRequest constructs an HTTP request from a method, target URL, and body reader. It returns both a request and an error, so callers must handle invalid input before sending the request. section 7.3.1 section 6.5.2

Use the returned request as the input to an HTTP client:

  • Choose a standard method such as http.MethodGet and provide the target URL. section 7.3.1
  • Pass http.NoBody when the request does not need a body; provide another Reader for requests such as POST. section 6.5.2
  • Handle the construction error, then pass the request to http.Client.Do and inspect the response. section 7.3.1

Create and send a GET request

req, err := http.NewRequest(http.MethodGet, c.url, http.NoBody) if err != nil { return fmt.Errorf("creating a new request: %w", err) } res, err := http.DefaultClient.Do(req) if err != nil { return fmt.Errorf("sending request: %w", err) } if res.StatusCode == http.StatusOK { // process the response } section 7.3.1 section 6.5.2

Wrap request creation for tests

A test helper can call http.NewRequest, report errors through testing.TB, and mark itself with Helper(). This keeps setup concise and reports failures at the calling test line. httptest.NewRequest is a different convenience function: it panics when its method or target is invalid. section 8.7.3

How Go by Example covers it

How deep it goes
Explains arguments, errors, bodies, client use, and test helpers, but defers transport-pool internals.
Examples
Uses GET requests, http.NoBody, a command-line load tool, and a testing helper that rejects an invalid method.
What it assumes
Assumes HTTP request and client concepts while teaching body readers, error checks, contexts, and test-helper patterns.
What you can do after
Build it from scratch, send it through an HTTP client, or wrap it in a test helper with useful failure reporting.
How it connects
Connects HTTP requests with HTTP clients, HTTP responses, request bodies, contexts, test helpers, and testing.TB.

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.