Creating a simple Message Bus: Episode 3
I's been a while since the last post, hey! Let's waste no time and dive straight in. This is the one everything has been building toward. We have a producer that sends messages to the broker. We ha...

Source: DEV Community
I's been a while since the last post, hey! Let's waste no time and dive straight in. This is the one everything has been building toward. We have a producer that sends messages to the broker. We have a broker that stores them in topic queues. All that's missing is the consumer — the thing that actually reads those messages. Let's build it. The Consumer // internal/consumer/consumer.go type Consumer struct { host string port string topic string } Simple. It knows where the broker is and which topic it cares about. The interesting part is Subscribe: func (c *Consumer) Subscribe() ([]string, error) { conn, err := net.Dial("tcp", net.JoinHostPort(c.host, c.port)) if err != nil { return nil, err } defer conn.Close() fmt.Fprintf(conn, "%s\n", c.topic) var messages []string scanner := bufio.NewScanner(conn) for scanner.Scan() { messages = append(messages, scanner.Text()) } return messages, nil } We connect to the broker. We send the topic name we want to subscribe to, terminated with a newlin