func (self *Pump) subscribeRedis(channel string, msger *messenger.Messenger) { c, err := redis.Dial("tcp", os.Getenv("REDIS_ADDR")) if err != nil { panic(err) } defer c.Close() psc := redis.PubSubConn{c} psc.Subscribe(channel) for { switch v := psc.Receive().(type) { case redis.Message: fmt.Printf("PMessage: channel:%s data:%s\n", v.Channel, v.Data) msger.SendMessage(string(v.Data)) case redis.Subscription: log.Printf("Subscription: kind:%s channel:%s count:%d\n", v.Kind, v.Channel, v.Count) if v.Count == 0 { return } case error: log.Printf("error: %v\n", v) return } } }
func (self *Pump) Start(allowCrossDomain bool) { r := mux.NewRouter() r.HandleFunc("/subscribe/{event}", func(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) event := vars["event"] self.runMsger(event, resp, allowCrossDomain) // Done. log.Println("Finished HTTP request at ", req.URL.Path) }) r.HandleFunc("/subscribe/{event}/{id:[0-9]}+", func(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) event := vars["event"] eventId := vars["id"] msgerName := fmt.Sprintf("%v.%v", event, eventId) self.runMsger(msgerName, resp, allowCrossDomain) // Done. log.Println("Finished HTTP request at ", req.URL.Path) }) r.HandleFunc("/publish/{event}", func(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) name := vars["event"] var msger *messenger.Messenger if self.msgers[name] == nil { msger = messenger.New(name) self.RegisterMessenger(name, msger) log.Println("SNS endpoint: listening /publish/" + msger.Name()) log.Println("SSE endpoint: listening /subscribe/" + msger.Name()) } else { msger = self.msgers[name] } n := sns.NewFromRequest(req) msger.SendMessage(n.Message) }) log.Println("HTTP server port " + self.port) http.ListenAndServe(self.port, r) }