Sobes.tech
Middle+

How would you design this code for use in different transport protocols (gRPC, HTTP, consumer)?

sobes.tech AI

Answer from AI

To support different transport protocols (gRPC, HTTP, consumer), it is advisable to define abstractions and separate the logic:

  1. Business logic interface — a separate layer that does not depend on the protocol. For example, an interface with methods for processing requests.

  2. Transport adapters — separate implementations that accept requests from specific protocols, transform them into the business logic format, and call the corresponding methods.

  3. Error handling and serialization — each adapter is responsible for transforming errors and data into a format understandable by the protocol client.

Example of an interface:

// Service describes the business logic
type Service interface {
    ProcessRequest(ctx context.Context, req Request) (Response, error)
}

For gRPC, create a server that calls Service.ProcessRequest. For HTTP, create an HTTP handler that parses JSON, calls ProcessRequest, and returns JSON. For consumer, create a message handler that deserializes the message, calls ProcessRequest, and sends a response.

This approach allows reusing business logic without duplication and easily adding new protocols.