44 lines
742 B
Go
44 lines
742 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var (
|
|
upgrader = websocket.Upgrader{
|
|
ReadBufferSize: 1024,
|
|
WriteBufferSize: 1024,
|
|
}
|
|
)
|
|
|
|
func websocketConnection(w http.ResponseWriter, r *http.Request) {
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
_, _ = fmt.Fprint(w, "You must use the web socket protocol to connect to this endpoint.", err)
|
|
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")))
|
|
|
|
http.ListenAndServe(":8080", nil)
|
|
}
|