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
