I am trying to build a feature with the redis pub/sub implementation on golang but for every client connected to the server (WebSocket) the number of messages published doubles.
func (c client) Subscribe() {
con := initRedis()
defer con.Close()
psc := redis.PubSubConn{Conn: con}
defer psc.Close()
psc.Subscribe(c.Channel)
for {
switch v := psc.Receive().(type) {
case redis.Message:
fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
broadcast <- map[string]string{
"channel": v.Channel,
"message": string(v.Data),
}
case redis.Subscription:
fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
log.Println(v)
psc.Unsubscribe()
}
}
}
func (m Message) Publish() {
c := initRedis()
defer c.Close()
reply, err := c.Do("PUBLISH", m.Channel, m.Msg)
if err != nil {
log.Println(err)
}
fmt.Println("Publishing", m, reply)
}
func initRedis() redis.Conn {
if err := godotenv.Load(); err != nil {
panic(err)
}
// fmt.Println(os.Getenv("REDIS_URL"))
c, err := redis.DialURL(os.Getenv("REDIS_URL"), redis.DialTLSSkipVerify(true))
if err != nil {
panic(err)
}
// defer c.Close()
return c
}
How do I stop the duplicates? or what is causing the duplicates.