diff options
-rw-r--r-- | .gitignore | 4 | ||||
-rw-r--r-- | Makefile | 7 | ||||
-rw-r--r-- | src/helsinki.at/rhrdtime/rhrdtime.go | 57 |
3 files changed, 62 insertions, 6 deletions
@@ -1 +1,3 @@ -bin/
\ No newline at end of file +bin/ +pkg/ +src/github.com
\ No newline at end of file @@ -27,7 +27,9 @@ GOCMD := go getlibs: export GOPATH=$(curdir) getlibs: -# $(GOCMD) get "<url for lib" + $(GOCMD) get "github.com/codegangsta/martini" + $(GOCMD) get "github.com/gorilla/websocket" + $(GOCMD) get "github.com/tuxychandru/pubsub" build: export GOPATH=$(curdir) build: getlibs @@ -38,8 +40,7 @@ clean: rm -rf bin distclean: clean -# rm -rf src/github.com -# rm -rf src/code.google.com + rm -rf src/github.com rm -rf pkg all: build test 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) } |