From 70f1f8f8198043273e0f41bffd144dbebf75f738 Mon Sep 17 00:00:00 2001 From: Amit Saha Date: Thu, 1 Sep 2022 06:23:37 +1000 Subject: [PATCH] Fix: Publish client-slow-write code Fix for issue https://github.com/practicalgo/code/issues/7 --- chap7/client-slow-write/go.mod | 3 +++ chap7/client-slow-write/main.go | 48 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 chap7/client-slow-write/go.mod create mode 100644 chap7/client-slow-write/main.go diff --git a/chap7/client-slow-write/go.mod b/chap7/client-slow-write/go.mod new file mode 100644 index 0000000..8626ef9 --- /dev/null +++ b/chap7/client-slow-write/go.mod @@ -0,0 +1,3 @@ +module github.com/practicalgo/code/chap7/client-slow-write + +go 1.16 diff --git a/chap7/client-slow-write/main.go b/chap7/client-slow-write/main.go new file mode 100644 index 0000000..3d4d119 --- /dev/null +++ b/chap7/client-slow-write/main.go @@ -0,0 +1,48 @@ +package main + +import ( + "context" + "fmt" + "io" + "log" + "net/http" + "time" +) + +func longRunningProcess(w *io.PipeWriter) { + for i := 0; i <= 10; i++ { + fmt.Fprintf(w, "hello") + time.Sleep(1 * time.Second) + } + w.Close() +} + +func main() { + + client := http.Client{} + logReader, logWriter := io.Pipe() + go longRunningProcess(logWriter) + r, err := http.NewRequestWithContext( + context.Background(), + "POST", + "http://localhost:8080/api/users/", + logReader, + ) + if err != nil { + log.Fatal(err) + } + + log.Printf("Starting client request") + + resp, err := client.Do(r) + if err != nil { + log.Fatalf("Error when sending the request: %v\n", err) + } + + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + log.Println(string(data)) +}