main.go 1.6 KB

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