Created
June 11, 2014 15:39
-
-
Save mackee/a2289882a316b23ee31e to your computer and use it in GitHub Desktop.
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 ( | |
"bytes" | |
"io" | |
"log" | |
"net/http" | |
) | |
var broadcastMessages = make(chan []byte) | |
func StreamHandler(w http.ResponseWriter, req *http.Request) { | |
for { | |
message, ok := <-broadcastMessages | |
if !ok { | |
break | |
} | |
w.Write(append(message, []byte("\n")...)) | |
w.(http.Flusher).Flush() | |
} | |
} | |
func BroadcastHandler(w http.ResponseWriter, req *http.Request) { | |
var buf bytes.Buffer | |
buf.ReadFrom(req.Body) | |
broadcastMessages <- buf.Bytes() | |
io.WriteString(w, "{ \"result\": \"ok\"}") | |
} | |
func EofHandler(w http.ResponseWriter, req *http.Request) { | |
close(broadcastMessages) | |
io.WriteString(w, "{ \"result\": \"ok\"}") | |
broadcastMessages = make(chan []byte) | |
} | |
func main() { | |
http.HandleFunc("/stream", StreamHandler) | |
http.HandleFunc("/broadcast", BroadcastHandler) | |
http.HandleFunc("/eof", EofHandler) | |
err := http.ListenAndServe(":8080", nil) | |
if err != nil { | |
log.Fatal("Can't start server. Check please port") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment