Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Last active April 21, 2020 21:08
Show Gist options
  • Save cirocosta/6872def77df4d1c2148ca8dba69731ff to your computer and use it in GitHub Desktop.
Save cirocosta/6872def77df4d1c2148ca8dba69731ff to your computer and use it in GitHub Desktop.
demonstrating ResponseWriter.Write blocking
# run a server
./a.out -server
# run a client
./a.out
# see that the server does not finish writing right away
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"time"
)
func server() (err error) {
buf := make([]byte, 1<<12)
http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
start := time.Now()
defer func() {
fmt.Println("elapsed", time.Now().Sub(start))
}()
for i := 0; i < 1000; i++ {
n, err := w.Write(buf)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("wrote", i, n)
}
})
err = http.ListenAndServe(":8000", nil)
if err != nil {
err = fmt.Errorf("listen and serve: %w", err)
return
}
return
}
func client() (err error) {
resp, err := http.Get("http://localhost:8000")
if err != nil {
err = fmt.Errorf("get: %w", err)
return
}
var (
buf []byte
n int
)
for {
buf = make([]byte, 1<<10)
fmt.Println("reading")
n, err = resp.Body.Read(buf)
if err != nil {
if err == io.EOF {
err = nil
return
}
err = fmt.Errorf("read: %w", err)
return
}
fmt.Println("read", n)
time.Sleep(10 * time.Millisecond)
}
return
}
var (
isServer = flag.Bool("server", false, "be a server?")
)
func main() {
var err error
flag.Parse()
if *isServer {
err = server()
} else {
err = client()
}
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment