-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
64 lines (49 loc) · 1.66 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
package main
import (
"log"
"net/http"
"io"
"sync"
)
type Stream struct {
reader io.ReadCloser
done chan struct{}
}
func main() {
log.Println("Starting up")
channels := make(map[string]chan Stream)
mutex := &sync.Mutex{}
handler := func(w http.ResponseWriter, r *http.Request) {
mutex.Lock()
_, ok := channels[r.URL.Path]
if !ok {
channels[r.URL.Path] = make(chan Stream)
}
channel := channels[r.URL.Path]
mutex.Unlock()
log.Println(channel)
if r.Method == "GET" {
select {
case stream := <-channel:
io.Copy(w, stream.reader)
close(stream.done)
case <-r.Context().Done():
log.Println("consumer canceled")
}
} else if r.Method == "POST" {
doneSignal := make(chan struct{})
stream := Stream{reader: r.Body, done: doneSignal}
select {
case channel <- stream:
log.Println("connected to consumer")
case <-r.Context().Done():
log.Println("producer canceled")
}
<-doneSignal
}
}
err := http.ListenAndServe(":9001", http.HandlerFunc(handler))
if err != nil {
log.Fatal(err)
}
}