package main import ( "container/ring" "net/http" "time" "github.com/gin-gonic/gin" melody "gopkg.in/olahol/melody.v1" ) func main() { gin.SetMode(gin.ReleaseMode) r := gin.Default() m := melody.New() history := ring.New(10) pub := ring.New(10) r.Static("/assets", "./assets") r.StaticFile("/", "./index.html") r.GET("/ws", func(c *gin.Context) { m.HandleRequest(c.Writer, c.Request) }) r.POST("/update", func(c *gin.Context) { metadata := c.PostForm("metadata") c.JSON(http.StatusOK, gin.H{ "status": "ok", }) if metadata == "" { return } for i := 0; i < history.Len(); i++ { history = history.Next() if history.Value == metadata { return } } history.Value = metadata history = history.Next() go func() { time.Sleep(time.Second * 10) for i := 0; i < pub.Len(); i++ { pub = pub.Next() if pub.Value == metadata { return } } pub.Value = metadata pub = pub.Next() m.Broadcast([]byte(metadata)) }() }) m.HandleConnect(func(s *melody.Session) { for i := 0; i < pub.Len(); i++ { if pub.Value != nil { s.Write([]byte(pub.Value.(string))) } pub = pub.Next() } }) r.Run(":1338") }