Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm working on an IoT service that needs to be able to send messages via some kind of protocol. My goal is to make it easy for me to swap between these protocol implementations.

In IoT two common protocols that are used for messaging are MQTT and WAMP. Both popular Go libraries for these protocols have similar interfaces, however different parameters for their respective function implementations.


Example:

MQTT

Publish(topic string, qos byte, retained bool, payload interface{}) Token

WAMP

Publish(topic string, options wamp.Dict, args wamp.List, kwargs wamp.Dict) error

My initial idea was to define a generic interface where I filter out all the parameters I really need:

Publish(topic string, payload map[string]interface{}, options map[string]interface{}) map[string]interface{}

However since for both libraries, the signatures are quite different, I am be forced to use the interface{}type. Which in turn would force me to do a lot of type assertion magic and extra work to make this work properly.

Am I completely missing something obvious? What would be a better solution to this problem? Or should I tackle this problem completely differently.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

I'd suggest creating your own API (define it the way you need it) and then build a wrapper around each of those libraries implementing your API. In each wrapper you can then apply the feature you need the way the library implements it. (I guess that is what you are trying.)

The Publish function could look like:

Publish(topic string, payload map[string]interface{}) error

The payload can easily be converted to wamp.Dict as that is also a map[string]interfac{}. It can also be passed to MQTT as that accepts any interface{}.

Don't try to pass in the options from the outside. Instead set them as needed in the wrappers. Or if you need to set them differently from outside, define your own and interpret them as needed for each package.

Only return an error. In case of MQTT interpret the Token correctly inside the wrapper for MQTT.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...