Standard library / net/http/httputil

httputil.ServerConn.Write()

Write the response for a previously read request in request order. Legacy-only: use net/http Client or Server for new code. Expected stdout: 'ok 0\n'.

Formal Syntax & Structure

go syntaxgo
func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error

Parameters & Attributes

NameTypeDescription
req*http.RequestHTTP request to inspect or exchange. Use only synthetic data in dumps.
resp*http.ResponseHTTP response to serialize or write.

Return Value

error

Nil on success, otherwise the operation error.

Working Example

Example Snippetgo
package main
import (  "bufio"  "fmt"  "io"  "net"  "net/http"  "net/http/httputil"  "strings"  "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)))  sc := httputil.NewServerConn(s, nil)  done := make(chan error, 1)  go func() { _, e := io.WriteString(c, "GET /a HTTP/1.1\r\nHost: demo.invalid\r\n\r\n"); done <- e }()  r := must(sc.Read())  check(<-done)  got := make(chan string, 1)  go func() {    res := must(http.ReadResponse(bufio.NewReader(c), r))    defer res.Body.Close()    got <- string(must(io.ReadAll(res.Body)))  }()  res := &http.Response{StatusCode: 200, ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok")), ContentLength: 2}  check(sc.Write(r, res))  fmt.Println(<-got, sc.Pending())  check(sc.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