forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.go
80 lines (68 loc) · 1.96 KB
/
demo.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 service
import (
"html/template"
"net/http"
"github.com/NYTimes/gizmo/server"
"github.com/NYTimes/gizmo/web"
)
// Demo will serve an HTML page that demonstrates how to use the 'stream'
// endpoint.
func (s *StreamService) Demo(w http.ResponseWriter, r *http.Request) {
vals := struct {
Port int
StreamID int64
}{
s.port,
web.GetInt64Var(r, "stream_id"),
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := demoTempl.Execute(w, &vals)
if err != nil {
server.Log.Error("template error ", err)
http.Error(w, "problems loading HTML", http.StatusInternalServerError)
}
}
var demoTempl = template.Must(template.New("demo").Parse(demoHTML))
const demoHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<title>StreamService Demo</title>
</head>
<body>
<h1>Welcome to the stream for {{ .StreamID }}!</h1>
<p>Open multiple tabs to see messages broadcast across all views</p>
<div id="consumed" style="float:left; width:50%">
</div>
<div id="published" style="float:left">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
(function()
{
var conn = new WebSocket(
"ws://localhost:{{ .Port }}/svc/v1/stream/{{ .StreamID }}"
);
// consume from websocket/Kafka
conn.onmessage = function(evt)
{
var evts = $("#consumed");
evts.prepend("<p> Received: " + evt.data + "</p>");
}
// publish to websocket/Kafka
setInterval(publishMessage(conn), 1000);
function publishMessage(conn) {
return function() {
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var msg = '{"game":"crossword","user_id":12345,"time":'+new Date().getTime()+',"cell":' + Math.floor(
(Math.random() * 10) + 1) +
',"value":"' + alpha.charAt(Math.floor(
Math.random() * alpha.length)) + '"}'
conn.send(msg);
var evts = $("#published");
evts.prepend("<p> Sent: " + msg + "</p>");
}
}
})();
</script>
</body>
</html>`