48 lines
825 B
Go
48 lines
825 B
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
ReadBufferSize: 1024,
|
|
WriteBufferSize: 1024,
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return strings.Contains(r.Host, "localhost")
|
|
},
|
|
}
|
|
|
|
func newConnection(w http.ResponseWriter, r *http.Request) {
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
fmt.Fprintf(w, "An error has occured: %s.\n", err)
|
|
return
|
|
}
|
|
defer ws.Close()
|
|
|
|
newSession(ws)
|
|
for {
|
|
_, p, err := ws.ReadMessage()
|
|
if err != nil {
|
|
disconnectSession(ws)
|
|
break
|
|
}
|
|
|
|
msg := string(p)
|
|
handleIncomingMessage(ws, msg)
|
|
}
|
|
}
|
|
|
|
func StartServer(port int) {
|
|
hostLocation := ":" + strconv.Itoa(port)
|
|
http.HandleFunc("/ws", newConnection)
|
|
|
|
log.Fatal(http.ListenAndServe(hostLocation, nil))
|
|
}
|