go-websockets-talk/code/main.go

45 lines
820 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")))
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Errorf("Server could not start up: %s", err.Error())
}
}