-
Notifications
You must be signed in to change notification settings - Fork 20
/
backpressure-02.go
80 lines (69 loc) · 1.49 KB
/
backpressure-02.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"sync"
"time"
)
type request struct {
r *http.Request
ch chan []byte
}
func newRequest(r *http.Request) request {
return request{
r: r,
ch: make(chan []byte),
}
}
func main() {
// We create a buffered channel with a max capacity of 1000 items.
// If the queue is full, drop the requests.
q := make(chan request, 100)
h := func(w http.ResponseWriter, r *http.Request) {
if len(q) < cap(q) {
req := newRequest(r) // Process the request.
q <- req // Send to queue.
w.Write(<-req.ch) // Wait for the reply.
} else {
w.Write([]byte("x")) // Drop the request.
}
}
ts := httptest.NewServer(http.HandlerFunc(h))
defer ts.Close()
// Process the request in the background.
go process(q)
makeRequests(ts.URL, 500, 6*time.Millisecond)
log.Println("second round")
time.Sleep(1 * time.Second)
makeRequests(ts.URL, 500, 6*time.Millisecond)
}
func process(q chan request) {
for r := range q {
// Sleep to simulate delay.
time.Sleep(10 * time.Millisecond)
// Send resp.
r.ch <- []byte("o")
}
}
func makeRequests(url string, count int, cooldown time.Duration) {
wg := sync.WaitGroup{}
for i := 0; i < count; i++ {
go func() {
wg.Add(1)
defer wg.Done()
resp, err := http.Get(url)
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(b))
}()
time.Sleep(cooldown)
}
wg.Wait()
}