Standard library / net/http/httputil

httputil.ClientConn.Do()

Write a request then read its response. A valid response may accompany ErrPersistEOF. Legacy-only: use net/http Client or Server for new code. Expected stdout: 'ok\n'.

Formal Syntax & Structure

go syntaxgo
func (cc *ClientConn) Do(req *http.Request) (*http.Response, error)

Parameters & Attributes

NameTypeDescription
req*http.RequestHTTP request to inspect or exchange. Use only synthetic data in dumps.

Return Value

(*http.Response, error)

Response and error; a valid response can accompany ErrPersistEOF.

Working Example

Example Snippetgo
package main
import (  "bufio"  "fmt"  "io"  "net"  "net/http"  "net/http/httputil"  "time")
func main() {  c, s := net.Pipe()  defer c.Close()  defer s.Close()  check(c.SetDeadline(time.Now().Add(3 * time.Second)))  check(s.SetDeadline(time.Now().Add(3 * time.Second)))  cc := httputil.NewClientConn(c, nil)  req := must(http.NewRequest("GET", "http://demo.invalid/a", nil))  done := make(chan error, 1)  go func() {    r, e := http.ReadRequest(bufio.NewReader(s))    if e != nil {      done <- e      return    }    r.Body.Close()    _, e = io.WriteString(s, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")    done <- e  }()  res := must(cc.Do(req))  fmt.Println(string(must(io.ReadAll(res.Body))))  check(res.Body.Close())  check(<-done)  check(cc.Close())}
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