radioweb/main.go
2019-04-05 01:02:36 +02:00

70 lines
1.2 KiB
Go

package main
import (
"container/ring"
"net/http"
"strings"
"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)
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "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")
if strings.HasPrefix(metadata, "/srv/audio/") {
metadata = strings.Replace(metadata, "/srv/audio/", "", 1)
}
if metadata == "" {
c.JSON(http.StatusBadRequest, gin.H{
"status": "failure",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "success",
})
for j := 0; j < 10; j++ {
if history.Value == metadata {
history = history.Next()
return
}
history = history.Next()
}
m.Broadcast([]byte(metadata))
history.Value = metadata
history = history.Next()
})
m.HandleConnect(func(s *melody.Session) {
for j := 0; j < 10; j++ {
if history.Value != nil {
s.Write([]byte(history.Value.(string)))
}
history = history.Next()
}
})
r.Run(":1338")
}