Skip to content

Instantly share code, notes, and snippets.

@davidalpert
Last active June 1, 2021 13:26
Show Gist options
  • Save davidalpert/77c547a9acc99f09f3e079a0d722aded to your computer and use it in GitHub Desktop.
Save davidalpert/77c547a9acc99f09f3e079a0d722aded to your computer and use it in GitHub Desktop.
package main
import (
"context"
kitlog "github.com/go-kit/kit/log"
"github.com/philippseith/signalr"
"net/http"
"os"
)
// define a struct to wrap signalr.Hub
type chat struct {
signalr.Hub
}
func main() {
// create an instances of my hub struct
hub := &chat{}
// use signalr.SimpleHubFactory to build a signalr.Server which uses my hub instance
server, _ := signalr.NewServer(context.TODO(),
signalr.SimpleHubFactory(hub),
signalr.KeepAliveInterval(2*time.Second),
signalr.Logger(kitlog.NewLogfmtLogger(os.Stderr), true))
// bind the signalr.Server to /chat using a router which can serve other endpoints
router := http.NewServeMux()
server.MapHTTP(router, "/chat")
// run that router in a non-blocking goroutine
go runHTTPServer("localhost:8086", router)
// ...later...
// now I want to broadcast from the server code to all/any connected clients
// I expect that my hub instance is able to broadcast but this next line panics
// because my hub struct doesn't seem to have any connections initialized when
// used outside of a client-initiated callback
hub.Clients().All().Send("msg", "payload")
// I've been experimenting in a branch with making the signalr.hubLifetimeManager public
// and embedding that interface directly in the signalr.Server so that any server instance
// can act like a signalr.HubLifetimeManager
//
// server.InvokeAll("msg", []interface{}{"payload"})
//
// in this way server code can hold onto it's server instance and use that to broadcast
// out to any clients who are connected at the time.
//
// if this works and makes sense to do I would suggest making the InvokeAll(..) signature
// variadic so declaring the []interface{}{} is implicit
//
// server.InvokeAll("msg", "arg1", arg2)
//
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment