Standard library / net/http

http.Client.Do()

Send a prepared request using the client policy. Non-2xx status is not itself a transport error. Expected stdout: '200 hello\n'.

Formal Syntax & Structure

go syntaxgo
func (c *Client) Do(req *Request) (*Response, error)

Parameters & Attributes

NameTypeDescription
req*RequestHTTP request associated with the operation.

Return Value

(*Response, error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "fmt"  "io"  "net/http"  "net/http/httptest")
func main() {  s := fixture()  defer s.Close()  q := must(http.NewRequest("GET", s.URL, nil))  r := must(s.Client().Do(q))  defer r.Body.Close()  fmt.Println(r.StatusCode, string(must(io.ReadAll(r.Body))))}func fixture() *httptest.Server {  return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {    w.Header().Set("X-Demo", "yes")    if r.Method == "POST" {      b, e := io.ReadAll(io.LimitReader(r.Body, 1025))      check(e)      if len(b) > 1024 {        w.WriteHeader(413)        return      }      fmt.Fprint(w, string(b))      return    }    fmt.Fprint(w, "hello")  }))}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference