draw-wip
This commit is contained in:
94
src/draw/draw.go
Normal file
94
src/draw/draw.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package draw
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/gommon/log"
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
var (
|
||||
wsConnections = make(map[*websocket.Conn]bool)
|
||||
wsMutex sync.Mutex
|
||||
)
|
||||
|
||||
func handleWsError(err error, conn *websocket.Conn) {
|
||||
if err != nil {
|
||||
log.Errorf("Failed to handle websocket: %v", err)
|
||||
conn.Close()
|
||||
wsMutex.Lock()
|
||||
defer wsMutex.Unlock()
|
||||
delete(wsConnections, conn)
|
||||
}
|
||||
}
|
||||
|
||||
func broadcastMessage(message string, ws *websocket.Conn) {
|
||||
wsMutex.Lock()
|
||||
defer wsMutex.Unlock()
|
||||
|
||||
for conn := range wsConnections {
|
||||
// if ws == conn {
|
||||
// continue
|
||||
// }
|
||||
err := websocket.Message.Send(conn, message)
|
||||
handleWsError(err, conn)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func formatMessage(index int, checked bool) string {
|
||||
message := "u:" + strconv.Itoa(index)
|
||||
if checked {
|
||||
message += ":+"
|
||||
} else {
|
||||
message += ":-"
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func forwardMessages(msg string, ws *websocket.Conn) error {
|
||||
if strings.Contains(msg, "ping") {
|
||||
len := len(wsConnections)
|
||||
websocket.Message.Send(ws, "pong-"+strconv.Itoa(len))
|
||||
return nil
|
||||
}
|
||||
|
||||
broadcastMessage(msg, ws)
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func InitWs(c echo.Context) error {
|
||||
log.Info("initWS")
|
||||
|
||||
websocket.Handler(func(ws *websocket.Conn) {
|
||||
wsMutex.Lock()
|
||||
wsConnections[ws] = true
|
||||
wsMutex.Unlock()
|
||||
|
||||
for {
|
||||
var msg string
|
||||
err := websocket.Message.Receive(ws, &msg)
|
||||
handleWsError(err, ws)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
forwardMessages(msg, ws)
|
||||
log.Infof("Received message: %s", msg)
|
||||
}
|
||||
}).ServeHTTP(c.Response(), c.Request())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Data struct {
|
||||
Template string
|
||||
}
|
||||
|
||||
func Page(c echo.Context) error {
|
||||
return c.Render(200, "index2", Data{Template: "draw"})
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/labstack/gommon/log"
|
||||
"knet.sk/src/draw"
|
||||
)
|
||||
|
||||
type Templates struct {
|
||||
@@ -54,6 +55,9 @@ func main() {
|
||||
|
||||
e.GET("/ws", initWs)
|
||||
|
||||
e.GET("/draw", draw.Page)
|
||||
e.GET("/draw/ws", draw.InitWs)
|
||||
|
||||
e.Logger.Fatal(e.Start(":54321"))
|
||||
|
||||
defer db.Close()
|
||||
|
||||
Reference in New Issue
Block a user