gmqtt
gmqtt copied to clipboard
Modify topic before publishing
Hi,
We have some legacy devices that send to a topic that should be changed.
I tried to implement the modification of the message with a plugin that uses the server.OnMsgArrived hook, but it seems that I can modify the payload but not the topic.
here is the code:
func (t *Topicrw) OnMsgArrivedWrapper(pre server.OnMsgArrived) server.OnMsgArrived {
return func(ctx context.Context, client server.Client, req *server.MsgArrivedRequest) error {
fmt.Println("Msg arrived")
req.Publish.TopicName = []byte("/another/topic")
req.Message.Payload = []byte("my other payload")
req.Message.Topic = "/changed/topic"
return nil
}
}
Following the code described in this issue https://github.com/DrmagicE/gmqtt/issues/24. I tried to republish the message with this code:
func (t *Topicrw) OnMsgArrivedWrapper(pre server.OnMsgArrived) server.OnMsgArrived {
return func(ctx context.Context, client server.Client, req *server.MsgArrivedRequest) error {
fmt.Println("Msg arrived")
req.Publish.TopicName = []byte("/another/topic")
req.Message.Payload = []byte("my other payload")
req.Message.Topic = "/changed/topic"
m := req.Message
m.Topic = "/my/other/topic"
m.Payload = []byte("lets change the payload")
t.s.Publisher().Publish(m)
req.Drop()
return nil
}
}
With the code above, a new message is published to another topic and the incoming message is supressed.
Is this code the right way to go?
Thank you very much!!!