diff options
author | Christian Pointner <equinox@helsinki.at> | 2015-07-16 21:31:31 (GMT) |
---|---|---|
committer | Christian Pointner <equinox@helsinki.at> | 2015-07-16 21:31:31 (GMT) |
commit | 6edadf45491ead123387d74239de7dfa63cefb37 (patch) | |
tree | 66cf8bd8ae00b353f0a47525d8cf51909e85d1b1 /src | |
parent | 7928b2b512ccf0269c351a5f603adf2e88522c32 (diff) |
listening for websocket and initial ticker
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) } |