49 lines
919 B
Go
49 lines
919 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"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)
|
|
}
|
|
}
|
|
|
|
const port = 8080
|
|
|
|
func main() {
|
|
http.HandleFunc("/websocket", websocketConnection)
|
|
http.Handle("/", http.FileServer(http.Dir("./static")))
|
|
|
|
fmt.Println("Chat server opening on port", port)
|
|
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
|
|
if err != nil {
|
|
_ = fmt.Errorf("Server could not start up: %s", err.Error())
|
|
}
|
|
}
|