Use the signalr.PerConnectionHubFactory option to create a 1:1 mapping between client connections and hub instances. This allows a hub instance to persist for the entire lifetime of a connection, enabling you to maintain connection-specific state (like user sessions, counters, or personal data) without recreating the hub for every method call.
Lifecycle
- Connection Establishment: When a client connects, the factory function is called with the
connectionID. - Hub Creation: A new hub instance is created and stored in the server's connection map.
- Method Invocation: All subsequent method calls on that specific connection reuse the same hub instance.
- Connection Cleanup: When the connection closes, the hub instance is automatically removed from the map to prevent memory leaks.
package main
import (
"context"
"github.com/philippseith/signalr"
)
type ChatHub struct {
signalr.Hub
connectionID string
username string
messageCount int
}
func (h *ChatHub) OnConnected(connectionID string) {
h.connectionID = connectionID
h.messageCount = 0
}
func (h *ChatHub) SendMessage(message string) {
h.messageCount++
h.Clients().All().Send("ReceiveMessage", h.username, message)
}
func main() {
ctx := context.Background()
server, err := signalr.NewServer(ctx,
signalr.PerConnectionHubFactory(func(connectionID string) signalr.HubInterface {
return &ChatHub{}
}),
)
if err != nil {
panic(err)
}
_ = server
}