2019-09-23 12:18:00 +07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
2020-08-27 14:14:59 +07:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 1024,
|
|
|
|
WriteBufferSize: 1024,
|
|
|
|
}
|
2019-09-23 12:18:00 +07:00
|
|
|
|
|
|
|
func websocketConnection(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2019-09-23 23:23:21 +07:00
|
|
|
_, _ = fmt.Fprint(w, "You must use the web socket protocol to connect to this endpoint.", err)
|
2019-09-23 12:18:00 +07:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
for {
|
|
|
|
_, p, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
handleDisconnection(ws)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
msg := string(p)
|
|
|
|
handleIncomingMessage(ws, msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
http.HandleFunc("/websocket", websocketConnection)
|
|
|
|
http.Handle("/", http.FileServer(http.Dir("./static")))
|
|
|
|
|
2019-09-26 00:42:13 +07:00
|
|
|
err := http.ListenAndServe(":8080", nil)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Errorf("Server could not start up: %s", err.Error())
|
|
|
|
}
|
2019-09-23 12:18:00 +07:00
|
|
|
}
|