This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
JISQueueing/server/socket/socket.go

82 lines
1.8 KiB
Go

package socket
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
type WebsocketInterface struct {
Writer http.ResponseWriter
Request *http.Request
OnConnect func(who *websocket.Conn)
OnMessage func(who *websocket.Conn, msg string)
OnDisconnect func(who *websocket.Conn)
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
//return strings.Contains(r.Host, "localhost")
},
}
//DisplaySocket handles all socket calls from the display machine
func DisplaySocket(w http.ResponseWriter, r *http.Request) {
socketUpgrader(WebsocketInterface{
Writer: w,
Request: r,
OnConnect: onNewDisplay,
OnMessage: onDisplayMessage,
OnDisconnect: onDisplayDisconnect,
})
}
//KioskSocket handles all socket calls from the user-facing machine
func KioskSocket(w http.ResponseWriter, r *http.Request) {
socketUpgrader(WebsocketInterface{
Writer: w,
Request: r,
OnConnect: onNewKiosk,
OnMessage: onKioskMessage,
OnDisconnect: onKioskDisconnect,
})
}
//Staffsocket handles all socket calls from the connToTable machines
func StaffSocket(w http.ResponseWriter, r *http.Request) {
socketUpgrader(WebsocketInterface{
Writer: w,
Request: r,
OnConnect: onNewStaff,
OnMessage: onStaffMessage,
OnDisconnect: onStaffDisconnect,
})
}
func socketUpgrader(conn WebsocketInterface) {
ws, err := upgrader.Upgrade(conn.Writer, conn.Request, nil)
if err != nil {
fmt.Fprint(conn.Writer, "You must use the socket protocol", err)
return
}
defer ws.Close()
conn.OnConnect(ws)
for {
_, p, err := ws.ReadMessage()
if err != nil {
conn.OnDisconnect(ws)
break
}
msg := string(p)
conn.OnMessage(ws, msg)
}
}