-
-
Save gbbr/c6d9123317482e1c93232ab581ee1258 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"net/http" | |
"net/http/httptest" | |
"time" | |
) | |
func main() { | |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | |
defer func() { _ = req.Body.Close() }() // Best effort. | |
conn, _, err := w.(http.Hijacker).Hijack() | |
if err != nil { | |
println("Error hijack:", err.Error()) | |
return | |
} | |
_, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n")) // Best effort. | |
for buf, n := make([]byte, 1024), 0; err == nil; n, err = req.Body.Read(buf) { | |
println("Handler -->", string(buf[:n])) | |
_, _ = conn.Write([]byte("ack\n")) // Best effort. | |
} | |
if err != nil && err != io.EOF { | |
println("Unexpected error:", err.Error()) | |
} | |
})) | |
defer ts.Close() | |
r, w := io.Pipe() | |
end := make(chan struct{}) | |
go func() { | |
defer close(end) | |
defer func() { _ = w.Close() }() // Best effort. | |
for i := 0; i < 3; i++ { | |
println("Request body producer") | |
if _, err := w.Write([]byte("hello\n")); err != nil { | |
if err != io.EOF { | |
println("Unexpected error:", err.Error()) | |
} | |
break | |
} | |
time.Sleep(1e9) | |
} | |
}() | |
req, err := http.NewRequest(http.MethodPost, ts.URL, r) | |
if err != nil { | |
panic(err) | |
} | |
resp, err := (&http.Client{}).Do(req) | |
if err != nil { | |
panic(err) | |
} | |
println("http resp:", resp.StatusCode) | |
<-end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment