diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/helsinki.at/rhrdtime/rhrdtime.go | 57 |
1 files changed, 55 insertions, 2 deletions
diff --git a/src/helsinki.at/rhrdtime/rhrdtime.go b/src/helsinki.at/rhrdtime/rhrdtime.go index 21f0efc..9ad4048 100644 --- a/src/helsinki.at/rhrdtime/rhrdtime.go +++ b/src/helsinki.at/rhrdtime/rhrdtime.go @@ -24,8 +24,61 @@ package main -import "fmt" +import ( + "fmt" + "net/http" + "time" + + "github.com/codegangsta/martini" + "github.com/gorilla/websocket" + "github.com/tuxychandru/pubsub" +) + +func goTalkWithClient(w http.ResponseWriter, r *http.Request, ps *pubsub.PubSub) { + ws, err := websocket.Upgrade(w, r, nil, 1024, 1024) + if _, ok := err.(websocket.HandshakeError); ok { + http.Error(w, "Not a websocket handshake", 400) + return + } else if err != nil { + fmt.Println(err) + return + } + fmt.Println("Client connected", ws.RemoteAddr()) + + publish_to_all_chan := ps.Sub("timeupdate") + + for jsonupdate := range publish_to_all_chan { + if err := ws.WriteMessage(websocket.TextMessage, jsonupdate.([]byte)); err != nil { + ps.Unsub(publish_to_all_chan, "timeupdate") + return + } + } +} + +func RunMartini(ps *pubsub.PubSub) { + m := martini.Classic() + m.Get("/time", func(w http.ResponseWriter, r *http.Request) { + goTalkWithClient(w, r, ps) + }) + + m.Run() +} func main() { - fmt.Println("Hello world!") + ps := pubsub.New(1) + + ticker := time.NewTicker(time.Second * 1) + go func() { + for t := range ticker.C { + tj, err := t.MarshalJSON() + if err != nil { + fmt.Println(err) + return + } + fmt.Println("Tick at: ", t) + ps.Pub(tj, "timeupdate"); + } + }() + + RunMartini(ps) } |