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