Since you're passing the function as a parameter to another function, you don't get to control the way in which it is called. However, you do have total control over what happens inside the function - which means you can start a goroutine there:
func onMessageReceived(client MQTT.Client, message MQTT.Message) {
go func() {
fmt.Printf("%s
", message.Payload())
}()
}
So, onMessageReceived
itself will still be called synchronously by MQTT, but it will just start a goroutine and immediately return. You could also define a separate function and call that with go
instead of an anonymous function:
func onMessageReceived(client MQTT.Client, message MQTT.Message) {
go messageHandler(client, message)
}
func messageHandler(client MQTT.Client, message MQTT.Message) {
fmt.Printf("%s
", message.Payload())
}
That's just a matter of how you want to organize your code. If it's a short handler I'd probably stick with the anonymous function (short enough that you can see the entire anonymous func on one screen); for a longer function I'd break it up or break it out into a named function.
Since you can't pass in any extra parameters, if you want to use a WaitGroup
, it will have to be global:
var wg = new(sync.WaitGroup)
func onMessageReceived(client MQTT.Client, message MQTT.Message) {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Printf("%s
", message.Payload())
}()
}