Last active
December 15, 2016 22:30
-
-
Save maccman/5079809 to your computer and use it in GitHub Desktop.
This file contains 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
// 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