Browse Source

add implementation with websockets

Gildas Chabot 6 years ago
parent
commit
dd234f9e2c
2 changed files with 87 additions and 0 deletions
  1. 25 0
      index.html
  2. 62 0
      ms.go

+ 25 - 0
index.html

@@ -0,0 +1,25 @@
1
+<html>
2
+  <head>
3
+  </head>
4
+  <body>
5
+      <div>
6
+          <h2>Websocket</h2>
7
+          <p>Progress: <span id="websocket"></span></p>
8
+          <button onclick="websocket()">Listen</button>
9
+      </div>
10
+
11
+      <script>
12
+       function websocket() {
13
+         var socket = new WebSocket({{ .websocket }}, "protocolOne");
14
+         socket.onmessage = function (event) {
15
+           if (event.data === "done") {
16
+             document.getElementById("websocket").innerHTML = "done!";
17
+             socket.close();
18
+             return;
19
+           }
20
+           document.getElementById("websocket").innerHTML=event.data+"%";
21
+         }
22
+       }
23
+      </script>
24
+  </body>
25
+</html>

+ 62 - 0
ms.go

@@ -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
+}