Files
2026-03-02 19:57:35 +07:00

90 lines
1.7 KiB
Go

package main
import (
"context"
"encoding/json"
"log"
"os"
"os/signal"
"syscall"
"time"
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/server"
)
type ExampleData struct {
Time time.Time `json:"time"`
Data string `json:"data"`
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
log.Println("Received shutdown signal")
cancel()
}()
s, err := server.NewSafeWebsocketServerBuilder().
BaseHost("localhost").
BasePort(8080).
ApiKey("abcd").
Context(ctx).
HandleFuncWebsocket("/ws/test/", "data_1", 5_000, func(ctx context.Context, c chan []byte) {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
jsonBytes, err := json.Marshal(ExampleData{
Time: time.Now(),
Data: "data_1",
})
if err != nil {
continue
}
select {
case c <- jsonBytes:
case <-ctx.Done():
return
}
}
}
}).
HandleFuncWebsocket("/ws/test/", "data_2", 5_000, func(ctx context.Context, c chan []byte) {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
jsonBytes, err := json.Marshal(ExampleData{
Time: time.Now(),
Data: "data_2",
})
if err != nil {
continue
}
select {
case c <- jsonBytes:
case <-ctx.Done():
return
}
}
}
}).
Build()
if err != nil {
log.Fatal(err)
}
s.ListenAndServe()
}