main.go 1.9 KB

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