htmgo/extensions/websocket/ws/every.go
maddalax 34e816ff7c
Websocket Extension - Alpha (#22)
* wip

* merge

* working again

* refactor/make it a bit cleaner

* fix to only call cb for session id who initiated the event

* support broadcasting events to all clients

* refactor

* refactor into ws extension

* add go mod

* rename module

* fix naming

* refactor

* rename

* merge

* fix manager ws delete, add manager tests

* add metric page

* fixes, add k6 script

* fixes, add k6 script

* deploy docker image

* cleanup

* cleanup

* cleanup
2024-11-09 12:05:53 -06:00

29 lines
933 B
Go

package ws
import (
"github.com/maddalax/htmgo/extensions/websocket/internal/wsutil"
"github.com/maddalax/htmgo/extensions/websocket/session"
"github.com/maddalax/htmgo/framework/h"
"github.com/maddalax/htmgo/framework/service"
"time"
)
// Every executes the given callback every interval, until the socket is disconnected, or the callback returns false.
func Every(ctx *h.RequestContext, interval time.Duration, cb func() bool) {
socketId := session.GetSessionId(ctx)
locator := ctx.ServiceLocator()
manager := service.Get[wsutil.SocketManager](locator)
manager.RunIntervalWithSocket(string(socketId), interval, cb)
}
func Once(ctx *h.RequestContext, cb func()) {
// time is irrelevant, we just need to run the callback once, it will exit after because of the false return
Every(ctx, time.Millisecond, func() bool {
cb()
return false
})
}
func RunOnConnected(ctx *h.RequestContext, cb func()) {
Once(ctx, cb)
}