ms.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "math/rand"
  4. "net/http"
  5. "os"
  6. "strconv"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/gorilla/websocket"
  10. )
  11. func main() {
  12. port := "8080"
  13. if os.Getenv("PORT") != "" {
  14. port = os.Getenv("PORT")
  15. }
  16. rand.Seed(time.Now().Unix())
  17. router := gin.Default()
  18. router.LoadHTMLFiles("index.html")
  19. router.GET("/", func(c *gin.Context) {
  20. c.HTML(http.StatusOK, "index.html", gin.H{
  21. "websocket": "ws://localhost:" + port + "/ws",
  22. })
  23. })
  24. router.GET("/ws", websocketHandler(websocket.Upgrader{
  25. Subprotocols: []string{"protocolOne"},
  26. }))
  27. router.Run(":" + port)
  28. }
  29. func websocketHandler(upgrader websocket.Upgrader) func(c *gin.Context) {
  30. return func(c *gin.Context) {
  31. conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  32. if err != nil {
  33. c.AbortWithError(http.StatusInternalServerError, err)
  34. return
  35. }
  36. progress := 0
  37. for progress < 100 {
  38. if err := conn.WriteMessage(1, []byte(strconv.Itoa(progress))); err != nil {
  39. c.AbortWithError(http.StatusInternalServerError, err)
  40. return
  41. }
  42. progress += rand.Intn(2)
  43. time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
  44. }
  45. if err := conn.WriteMessage(1, []byte("done")); err != nil {
  46. c.AbortWithError(http.StatusInternalServerError, err)
  47. return
  48. }
  49. }
  50. }