updated ws sockets
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Paul 2023-03-12 14:25:40 +01:00
parent 697df68640
commit 0354fe3255
2 changed files with 44 additions and 10 deletions

View File

@ -155,5 +155,8 @@ func RegisterRoutes(e *echo.Echo, ctx *context.Context, cfg *config.Config) {
return Result(c, err, disc)
})
e.File("/test.html", "/home/paul/test.html")
e.GET("/ws", ws.HandleWS)
e.GET("/ws", func(c echo.Context) (err error) {
ws.HandleWS(c, cfg)
return
})
}

View File

@ -18,32 +18,54 @@ func Init(cfg *config.Config) {
LISTENERS = make(map[string]*websocket.Conn)
}
func HandleWS(c echo.Context) error {
func HandleWS(c echo.Context, cfg *config.Config) error {
websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
fmt.Printf("rr: %v\n", ws)
var lastip string
for {
var apievent = models.APIEvent{}
var event = models.Event{}
// Read
var event models.APIEvent
var msg []byte
err := websocket.Message.Receive(ws, &msg)
if err != nil {
log.Println(err)
return
}
err = json.Unmarshal(msg, &event)
err = json.Unmarshal(msg, &apievent)
if err != nil {
log.Println(err)
}
if event.MsgType == "bootstrap" {
LISTENERS[event.Hostname] = ws
if apievent.IPData.IP != "" && apievent.IPData.IP == lastip {
continue
}
switch apievent.MsgType {
case "bootstrap":
LISTENERS[apievent.Hostname] = ws
fmt.Println(LISTENERS)
case "add":
session := cfg.Db.NewSession()
event.APIParse(session, apievent)
session.Close()
err := event.Insert(cfg)
if err != nil {
log.Println(err)
}
log.Printf("zmq: Inserted event")
case "file":
apievent.MsgType = "ws"
}
fmt.Println(LISTENERS)
// Write
err = websocket.Message.Send(ws, "OK")
err = websocket.Message.Send(ws, "OK_sendtest")
if err != nil {
gcconn(ws)
fmt.Println(LISTENERS)
return
}
@ -51,3 +73,12 @@ func HandleWS(c echo.Context) error {
}).ServeHTTP(c.Response(), c.Request())
return nil
}
func gcconn(conn *websocket.Conn) (err error) {
for i, v := range LISTENERS {
if v == conn {
delete(LISTENERS, i)
}
}
return err
}