Skip to content

Commit 377c044

Browse files
committed
json over websocket
1 parent 9319614 commit 377c044

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

day29-web-server/webSocket.go

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
package main
22

33
import (
4-
_ "fmt"
4+
"fmt"
55
"github.com/gorilla/websocket"
66
"net/http"
7+
"time"
78
)
89

910
var upgrader = websocket.Upgrader{}
@@ -15,7 +16,7 @@ func main() {
1516
})
1617

1718
http.HandleFunc("/v1/ws", func(w http.ResponseWriter, r *http.Request) {
18-
conn, _ := upgrader.Upgrade(w, r, nil)
19+
conn, _ := upgrader.Upgrade(w, r, nil)
1920
go func(conn *websocket.Conn) {
2021

2122
for {
@@ -27,5 +28,38 @@ func main() {
2728

2829
})
2930

31+
http.HandleFunc("/v2/ws", func(w http.ResponseWriter, r *http.Request) {
32+
conn, _ := upgrader.Upgrade(w, r, nil)
33+
go func(conn *websocket.Conn) {
34+
35+
for {
36+
_, msg, _ := conn.ReadMessage()
37+
fmt.Println(string(msg))
38+
}
39+
40+
}(conn)
41+
42+
})
43+
44+
http.HandleFunc("/v3/ws", func(w http.ResponseWriter, r *http.Request) {
45+
conn, _ := upgrader.Upgrade(w, r, nil)
46+
go func(conn *websocket.Conn) {
47+
ch:= time.Tick(5* time.Second)
48+
for range ch{
49+
conn.WriteJSON(myStruct{
50+
User: "gunjan5",
51+
Name: "Gunjan Patel",
52+
})
53+
}
54+
55+
56+
}(conn)
57+
58+
})
59+
3060
http.ListenAndServe(":8080", nil)
3161
}
62+
type myStruct struct{
63+
User string `json:"user"`
64+
Name string `json:"name"`
65+
}

0 commit comments

Comments
 (0)