Created
February 22, 2016 01:37
-
-
Save jpillora/ab34fc518f4d57bbc146 to your computer and use it in GitHub Desktop.
another event source golang example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
"github.com/NYTimes/gziphandler" | |
"github.com/donovanhide/eventsource" | |
) | |
type TimeEvent time.Time | |
func (t TimeEvent) Id() string { return fmt.Sprint(time.Time(t).UnixNano()) } | |
func (t TimeEvent) Event() string { return "" } | |
func (t TimeEvent) Data() string { return time.Time(t).String() } | |
func main() { | |
eventsHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
s := eventsource.NewServer() | |
s.Gzip = true | |
go func() { | |
id := 1 | |
for { | |
e := TimeEvent(time.Now()) | |
s.Publish([]string{"time"}, &e) | |
id++ | |
if id == 10 { | |
break | |
} | |
time.Sleep(1 * time.Second) | |
} | |
s.Close() | |
}() | |
s.Handler("time").ServeHTTP(w, r) | |
}) | |
gzipEventsHandler := gziphandler.GzipHandler(eventsHandler) | |
http.Handle("/events", gzipEventsHandler) | |
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "text/html") | |
w.Write([]byte(index)) | |
})) | |
log.Println("listening 9000") | |
log.Fatal(http.ListenAndServe(":9000", nil)) | |
} | |
const index = `<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>event source test</title> | |
</head> | |
<body> | |
<div id="events"> | |
</div> | |
<script src="poly.js" type="text/javascript"></script> | |
<script type="text/javascript"> | |
console.log("hello") | |
var source = new EventSource("/events", { withCredentials: true }); | |
source.onmessage = function(e) { | |
console.log(e); | |
var elem = document.createElement("div"); | |
elem.innerHTML = "event: " + e.data; | |
events.appendChild(elem); | |
window.last = e; | |
}; | |
source.onerror = function(err) { | |
console.warn(err); | |
}; | |
source.onclose = function(err) { | |
console.info("closed", err); | |
}; | |
</script> | |
</body> | |
</html> | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment