Created
March 2, 2015 18:45
-
-
Save tt/3e7d85c89e07d1115242 to your computer and use it in GitHub Desktop.
Server-Sent Events 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 ( | |
"log" | |
"net/http" | |
"strconv" | |
"time" | |
"gopkg.in/antage/eventsource.v1" | |
) | |
func main() { | |
es := eventsource.New(nil, nil) | |
defer es.Close() | |
http.Handle("/events", es) | |
go func() { | |
id := 1 | |
for { | |
es.SendEventMessage("tick\n", "", strconv.Itoa(id)) | |
id++ | |
time.Sleep(time.Second) | |
} | |
}() | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte(`<html> | |
<pre></pre> | |
<script> | |
window.addEventListener("load", function() { | |
var evtSource = new EventSource("/events"); | |
evtSource.onmessage = function(e) { | |
var element = document.getElementsByTagName("pre")[0]; | |
element.insertAdjacentHTML("beforeend", e.data); | |
} | |
}) | |
</script> | |
</html>`)) | |
}) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment