123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package main
- import (
- "math/rand"
- "net/http"
- "os"
- "strconv"
- "time"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- )
- func main() {
- port := "8080"
- if os.Getenv("PORT") != "" {
- port = os.Getenv("PORT")
- }
- rand.Seed(time.Now().Unix())
- router := gin.Default()
- router.LoadHTMLFiles("index.html")
- router.GET("/", func(c *gin.Context) {
- c.HTML(http.StatusOK, "index.html", gin.H{
- "websocket": "ws://localhost:" + port + "/ws",
- })
- })
- router.GET("/ws", websocketHandler(websocket.Upgrader{
- Subprotocols: []string{"protocolOne"},
- }))
- router.Run(":" + port)
- }
- func websocketHandler(upgrader websocket.Upgrader) func(c *gin.Context) {
- return func(c *gin.Context) {
- conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- c.AbortWithError(http.StatusInternalServerError, err)
- return
- }
- progress := 0
- for progress < 100 {
- if err := conn.WriteMessage(1, []byte(strconv.Itoa(progress))); err != nil {
- c.AbortWithError(http.StatusInternalServerError, err)
- return
- }
- progress += rand.Intn(2)
- time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
- }
- if err := conn.WriteMessage(1, []byte("done")); err != nil {
- c.AbortWithError(http.StatusInternalServerError, err)
- return
- }
- }
- }
|