Skip to content

Commit abd9c83

Browse files
authored
Merge pull request #9 from practicalgo/issue_7
Fix: Publish client-slow-write code
2 parents bb899c0 + 70f1f8f commit abd9c83

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

chap7/client-slow-write/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/practicalgo/code/chap7/client-slow-write
2+
3+
go 1.16

chap7/client-slow-write/main.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"io"
7+
"log"
8+
"net/http"
9+
"time"
10+
)
11+
12+
func longRunningProcess(w *io.PipeWriter) {
13+
for i := 0; i <= 10; i++ {
14+
fmt.Fprintf(w, "hello")
15+
time.Sleep(1 * time.Second)
16+
}
17+
w.Close()
18+
}
19+
20+
func main() {
21+
22+
client := http.Client{}
23+
logReader, logWriter := io.Pipe()
24+
go longRunningProcess(logWriter)
25+
r, err := http.NewRequestWithContext(
26+
context.Background(),
27+
"POST",
28+
"http://localhost:8080/api/users/",
29+
logReader,
30+
)
31+
if err != nil {
32+
log.Fatal(err)
33+
}
34+
35+
log.Printf("Starting client request")
36+
37+
resp, err := client.Do(r)
38+
if err != nil {
39+
log.Fatalf("Error when sending the request: %v\n", err)
40+
}
41+
42+
defer resp.Body.Close()
43+
data, err := io.ReadAll(resp.Body)
44+
if err != nil {
45+
log.Fatal(err)
46+
}
47+
log.Println(string(data))
48+
}

0 commit comments

Comments
 (0)