-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (71 loc) · 1.74 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
package main
import (
"fmt"
"github.com/zimbatm/httputil2"
"html/template"
"log"
"net/http"
"os"
"time"
)
const homepageHtml = `
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var source = new EventSource("/events?channels={{.Channels}}");
source.addEventListener('message', function(e) {
console.log(e);
$("#messages").append("<p>" + e.data + "</p>");
}, false);
</script>
</head>
<body>
<form action="/send" method=GET>
<input name=channel value=foo>
<input name=data>
<input type=submit>
</form>
Look at all of the messages from the server:
<div id="messages"/>
</body>
</html>
`
type HomepageParams struct {
Channels string
}
var homepageTemplate = template.Must(template.New("home").Parse(homepageHtml))
func homePage(w http.ResponseWriter, req *http.Request) {
channels := req.URL.Query().Get("channels")
if len(channels) == 0 {
channels = "foo,bar"
}
homepageTemplate.Execute(w, HomepageParams{channels})
}
func main() {
var h http.Handler
serverAddr := ":9001"
redisAddr := ":6379"
pub := NewRedisPublisher(redisAddr)
sub := NewRedisSubscriber(redisAddr)
op := NewMultiplexer(sub)
mux := http.NewServeMux()
mux.HandleFunc("/", homePage)
mux.Handle("/events", NewSubscriberHandler(op))
mux.Handle("/send", NewPublisherHandler(pub))
h = httputil2.GzipHandler(mux)
h = httputil2.LogHandler(
h,
os.Stdout,
httputil2.CommonLogFormatter(httputil2.CommonLogFormat),
)
s := &http.Server{
Addr: serverAddr,
Handler: h,
ReadTimeout: 20 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
fmt.Printf("Starting app at %s\n", serverAddr)
log.Fatal(s.ListenAndServe())
}