Skip to content

Instantly share code, notes, and snippets.

@maccman
Last active December 15, 2016 22:30
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maccman/5079809 to your computer and use it in GitHub Desktop.
Save maccman/5079809 to your computer and use it in GitHub Desktop.
// Go PubSub Server
//
// Usage - Subscribing:
// var conn = new EventSource('/subscribe');
// conn.addEventListener('message', function(e){ alert(e.data); }, false);
//
// Usage - Publishing:
// curl http://localhost:8080/publish -F 'msg=Hello World'
package main
import (
"net/http"
)
var channels []chan string
func publish(w http.ResponseWriter, r *http.Request) {
msg := r.FormValue("msg")
for _, channel := range channels {
channel <- msg
}
w.WriteHeader(204)
}
func subscribe(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(200)
channel := make(chan string)
channels = append(channels, channel)
f, f_ok := w.(http.Flusher)
for {
msg := <-channel
w.Write([]byte("data: " + msg + "\n\n"))
if f_ok {
f.Flush()
}
}
}
func main() {
http.HandleFunc("/publish", publish)
http.HandleFunc("/subscribe", subscribe)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment