Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

go - Generic interface for API with common functionality but different function parameters

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.

question from:https://stackoverflow.com/questions/65834524/generic-interface-for-api-with-common-functionality-but-different-function-param

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...