Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created July 13, 2023 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/289171da514aa7ccd857024bde24c4ff to your computer and use it in GitHub Desktop.
Save ostretsov/289171da514aa7ccd857024bde24c4ff to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"time"
)
func main() {
go func() {
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
go func() {
for {
buf := make([]byte, 10)
if _, err := r.Body.Read(buf); err != nil {
panic(err)
}
fmt.Println("reading", string(buf))
}
}()
rc := http.NewResponseController(w)
for {
str := fmt.Sprintf("ping %d", time.Now().UnixNano())
if _, err := w.Write([]byte(str)); err != nil {
panic(err)
}
if err := rc.Flush(); err != nil {
panic(err)
}
fmt.Println("start sleep")
time.Sleep(5000 * time.Millisecond)
fmt.Println("end sleep")
}
}))
}()
reader, writer := io.Pipe()
go func() {
for {
_, err := writer.Write([]byte("request"))
if err != nil {
panic(err)
}
time.Sleep(1000 * time.Millisecond)
}
}()
u, _ := url.Parse("http://localhost:8080")
req := &http.Request{
Method: "POST",
ProtoMajor: 1,
ProtoMinor: 1,
URL: u,
TransferEncoding: []string{"chunked"},
Body: reader,
Header: make(map[string][]string),
}
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
for {
buf := make([]byte, 40)
if _, err := res.Body.Read(buf); err != nil {
panic(err)
}
fmt.Println(string(buf))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment