main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "io"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. router := gin.Default()
  9. router.LoadHTMLGlob("resources/*.templ.html")
  10. router.Static("/static", "resources/static")
  11. router.GET("/", index)
  12. router.GET("/room/:roomid", roomGET)
  13. router.POST("/room/:roomid", roomPOST)
  14. //router.DELETE("/room/:roomid", roomDELETE)
  15. router.GET("/stream/:roomid", streamRoom)
  16. router.Run(":8080")
  17. }
  18. func index(c *gin.Context) {
  19. c.Redirect(301, "/room/hn")
  20. }
  21. func roomGET(c *gin.Context) {
  22. roomid := c.ParamValue("roomid")
  23. userid := c.FormValue("nick")
  24. c.HTML(200, "room_login.templ.html", gin.H{
  25. "roomid": roomid,
  26. "nick": userid,
  27. "timestamp": time.Now().Unix(),
  28. })
  29. }
  30. func roomPOST(c *gin.Context) {
  31. roomid := c.ParamValue("roomid")
  32. nick := c.FormValue("nick")
  33. message := c.PostFormValue("message")
  34. if len(message) > 200 || len(nick) > 20 {
  35. c.JSON(400, gin.H{
  36. "status": "failed",
  37. "error": "the message or nickname is too long",
  38. })
  39. return
  40. }
  41. post := gin.H{
  42. "nick": nick,
  43. "message": message,
  44. }
  45. room(roomid).Submit(post)
  46. c.JSON(200, post)
  47. }
  48. func roomDELETE(c *gin.Context) {
  49. roomid := c.ParamValue("roomid")
  50. deleteBroadcast(roomid)
  51. }
  52. func streamRoom(c *gin.Context) {
  53. roomid := c.ParamValue("roomid")
  54. listener := openListener(roomid)
  55. ticker := time.NewTicker(1 * time.Second)
  56. defer closeListener(roomid, listener)
  57. defer ticker.Stop()
  58. c.Stream(func(w io.Writer) bool {
  59. select {
  60. case msg := <-listener:
  61. c.SSEvent("message", msg)
  62. case <-ticker.C:
  63. c.SSEvent("stats", Stats())
  64. }
  65. return true
  66. })
  67. }