gin-gonic和大猩猩/ websocket不传播消息

So I made a few changes to this example to make it work with gin-gonic https://github.com/utiq/go-in-5-minutes/tree/master/episode4

The websocket handshake between many clients is succesful. The problem is that when a client sends a message, the message is not propagated to the rest of the clients.

I had a look on your commit changes of episode4.

My observations as follows:

  • You're creating hub instance on every incoming request at stream handler. hub instance used to keeps track connections, etc. so you're losing it on every request.
  • You have removed index/home handler (may be you wanted to convert to gin handler or something, I don't know).

Now, let's bring episode4 into action. Please do following changes (as always improve it as you like). I have tested your episode4 with below changes, it's working fine.

Make /ws handler work on server.go:

h := newHub()
wsh := wsHandler{h: h}
r.GET("/ws", func(c *gin.Context) {
    wsh.ServeHTTP(c.Writer, c.Request)
})

Remove the stream handler on connection.go:

func stream(c *gin.Context) {
    h := newHub()
    wsHandler{h: h}.ServeHTTP(c.Writer, c.Request)
}

Adding index HTML handler on server.go: (added it to test episode4 at my end)

r.SetHTMLTemplate(template.Must(template.ParseFiles("index.html")))
r.GET("/", func(c *gin.Context) {
    c.HTML(200, "index.html", nil)
})