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)) +}