main.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "math/rand"
  6. "net/http"
  7. "github.com/gin-gonic/gin"
  8. )
  9. func main() {
  10. router := gin.Default()
  11. router.SetHTMLTemplate(html)
  12. router.GET("/room/:roomid", roomGET)
  13. router.POST("/room/:roomid", roomPOST)
  14. router.DELETE("/room/:roomid", roomDELETE)
  15. router.GET("/stream/:roomid", stream)
  16. router.Run(":8080")
  17. }
  18. func stream(c *gin.Context) {
  19. roomid := c.Param("roomid")
  20. listener := openListener(roomid)
  21. defer closeListener(roomid, listener)
  22. c.Stream(func(w io.Writer) bool {
  23. c.SSEvent("message", <-listener)
  24. return true
  25. })
  26. }
  27. func roomGET(c *gin.Context) {
  28. roomid := c.Param("roomid")
  29. userid := fmt.Sprint(rand.Int31())
  30. c.HTML(http.StatusOK, "chat_room", gin.H{
  31. "roomid": roomid,
  32. "userid": userid,
  33. })
  34. }
  35. func roomPOST(c *gin.Context) {
  36. roomid := c.Param("roomid")
  37. userid := c.PostForm("user")
  38. message := c.PostForm("message")
  39. room(roomid).Submit(userid + ": " + message)
  40. c.JSON(http.StatusOK, gin.H{
  41. "status": "success",
  42. "message": message,
  43. })
  44. }
  45. func roomDELETE(c *gin.Context) {
  46. roomid := c.Param("roomid")
  47. deleteBroadcast(roomid)
  48. }