henning77
henning77

Reputation: 3844

How to design a connector in go

I am building a simple connector component in go, with these responsibilities:

  1. Open, keep & manage connection to an external service (i.e. run in background).
  2. Parse incoming data into logical messages and pass these messages to business logic component.
  3. Send logical messages from business logic to external service.

I am undecided how to design the interface of the connector in go.

Variant A) Channel for inbound, function call for outbound messages

// Listen for inbound messages.
// Inbound messages are delivered to the provided channel.
func Listen(msg chan *Message) {...}

// Deliver msg to service
func Send(msg *Message) {...}

Variant B) Channel for inbound and outbound messages

// Listen for inbound messages + send outbound messages.
// Inbound messages are delivered to the provided msgIn channel.
// To send a message, put a message into the msgOut channel. 
func ListenAndSend(msgIn chan *Message, msgOut chan *Message) {...}

Variant B seems cleaner and more "go-like" to me, but I am looking for answers to:

Upvotes: 0

Views: 85

Answers (1)

thwd
thwd

Reputation: 24848

Both approaches allow for only one listener (unless you keep track of the amount of listeners, which is a somewhat fragile approach), which is a limitation. It all depends on your programmatic preferences but I'd probably go with callbacks for incoming messages and a send method:

func OnReceive(func(*Message) bool) // If callback returns false, unregister it.

func Send(*Message)

Other than that, both of your proposed models are completely valid. The second seems more "orthogonal". An advantage of using a send method is that you can make sure it never blocks, as opposed to a "bare" channel.

Upvotes: 3

Related Questions