-
-
Save hfeeki/5285995 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
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