Standard library / net/http/httputil
httputil.ClientConn.Read()
Read the next response after a corresponding request is written. Reads may overlap writes, not other reads; a response may accompany ErrPersistEOF. Legacy-only: use net/http Client or Server for new code. Expected stdout: '200\n'.
Formal Syntax & Structure
go syntaxgo
func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| req | *http.Request | HTTP request to inspect or exchange. Use only synthetic data in dumps. |
Return Value
(resp *http.Response, err 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 }() check(cc.Write(req)) res := must(cc.Read(req)) fmt.Println(res.StatusCode) 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) }}