-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
52 lines (42 loc) · 868 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
log.Println("connection successful")
for {
mt, msg, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
strMsg := bytes.NewBuffer(msg).String()
fmt.Println(strMsg)
serverMsg := []byte("this is server: " + strMsg)
conn.WriteMessage(mt, serverMsg)
}
}
func home(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
}
func main() {
http.HandleFunc("/", home)
http.HandleFunc("/chat", handler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}