-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
126 lines (96 loc) · 3.51 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"fmt"
"net/http"
"io"
"sync"
"strconv"
)
type Queue struct {
ch chan Transfer
numProducers int
numConsumers int
}
type Transfer struct {
reader io.Reader
size int
}
func NewQueue() *Queue {
return &Queue{
ch: make(chan Transfer),
}
}
func main() {
fmt.Println("Starting up")
queues := make(map[string]*Queue)
mut := &sync.Mutex{}
handle := func (w http.ResponseWriter, r *http.Request) {
channelId := r.URL.Path
if r.Method == "GET" {
mut.Lock()
queue, exists := queues[channelId]
if !exists {
queue = NewQueue()
queues[channelId] = queue
}
ch := queue.ch
queue.numConsumers += 1
mut.Unlock()
select {
case transfer := <-ch:
w.Header().Set("Content-Length", fmt.Sprintf("%d", transfer.size))
_, err := io.Copy(w, transfer.reader)
if err != nil {
if closer, ok := transfer.reader.(io.Closer); ok {
closer.Close()
}
}
case <-r.Context().Done():
}
mut.Lock()
queue.numConsumers -= 1
if queue.numConsumers == 0 && queue.numProducers == 0 {
delete(queues, channelId)
}
mut.Unlock()
fmt.Println(queues)
} else {
mut.Lock()
queue, exists := queues[channelId]
if !exists {
queue = NewQueue()
queues[channelId] = queue
}
ch := queue.ch
queue.numProducers += 1
mut.Unlock()
reader, writer := io.Pipe()
contentLength, err := strconv.Atoi(r.Header.Get("Content-Length"))
if err != nil {
contentLength = 0
}
transfer := Transfer{
reader: reader,
size: contentLength,
}
select {
case ch <- transfer:
io.Copy(writer, r.Body)
case <-r.Context().Done():
}
writer.Close()
mut.Lock()
queue.numProducers -= 1
if queue.numProducers == 0 && queue.numConsumers == 0 {
delete(queues, channelId)
}
mut.Unlock()
fmt.Println(queues)
}
}
http.HandleFunc("/", handle)
err := http.ListenAndServe(":9002", nil)
if err != nil {
fmt.Println(err)
}
}