Skip to content

Instantly share code, notes, and snippets.

@hfeeki
Forked from minikomi/server.go
Created April 1, 2013 16:29
Show Gist options
  • Save hfeeki/5285995 to your computer and use it in GitHub Desktop.
Save hfeeki/5285995 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
)
func broadcaster(in chan chan string, out chan chan string, listen chan string) {
chans := map[chan string]bool{}
for {
select {
case ch := <-in:
chans[ch] = true
case ch := <-out:
delete(chans, ch)
case s := <-listen:
for ch := range chans {
ch <- s
}
}
}
}
var (
subscribe = make(chan chan string)
unsubscribe = make(chan chan string)
publish = make(chan string)
)
func init() {
go broadcaster(subscribe, unsubscribe, publish)
}
func home(w http.ResponseWriter, r *http.Request) {
ch := make(chan string)
subscribe <- ch
defer func() {
unsubscribe <- ch
}()
fmt.Fprintln(w, <-ch)
}
func send(w http.ResponseWriter, r *http.Request) {
publish <- r.FormValue("msg")
fmt.Fprintln(w, "Sent!")
}
func main() {
http.HandleFunc("/", home)
http.HandleFunc("/send", send)
fmt.Println("Running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment