-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
99 lines (80 loc) · 1.92 KB
/
main.go
File metadata and controls
99 lines (80 loc) · 1.92 KB
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
package main
import (
"fmt"
"io"
"net/http"
"strings"
"sync"
)
var mutex = new(sync.Mutex)
// SSEChannel model
type SSEChannel struct {
Clients []chan string
Notifier chan string
}
var sseChannel SSEChannel
func main() {
fmt.Println("SSE-GO")
sseChannel = SSEChannel{
Clients: make([]chan string, 0),
Notifier: make(chan string),
}
done := make(chan interface{})
defer close(done)
go broadcaster(done)
http.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Connection doesnot support streaming", http.StatusBadRequest)
return
}
sseChan := make(chan string)
sseChannel.Clients = append(sseChannel.Clients, sseChan)
// this go routine reads and streams into the
// channel
d := make(chan interface{})
defer close(d)
defer fmt.Println("Closing channel.")
for {
select {
case <-d:
close(sseChan)
return
case data := <-sseChan:
fmt.Printf("data: %v \n\n", data)
fmt.Fprintf(w, "data: %v \n\n", data)
flusher.Flush()
}
}
})
http.HandleFunc("/log", logHTTPRequest)
fmt.Println("Listening to 5000")
http.ListenAndServe(":5000", nil)
}
func logHTTPRequest(w http.ResponseWriter, r *http.Request) {
buf := new(strings.Builder)
if _, err := io.Copy(buf, r.Body); err != nil {
fmt.Printf("Error: %v", err)
}
method := r.Method
logMsg := fmt.Sprintf("Method: %v, Body: %v", method, buf.String())
fmt.Println(logMsg)
sseChannel.Notifier <- logMsg
}
func broadcaster(done <-chan interface{}) {
fmt.Println("Broadcaster Started.")
for {
select {
case <-done:
return
case data := <-sseChannel.Notifier:
for _, channel := range sseChannel.Clients {
channel <- data
}
}
}
}