main.go
main.go - Overview
This file defines the core service logic for a chatroom application using DiceDB. It initializes a DiceDB client, provides functions for sending messages, subscribing to message updates, and listening for new messages.
Detailed Documentation
client
- Purpose: A package-level variable that holds the DiceDB client instance.
init
- Purpose: Initializes the DiceDB client when the package is loaded. It connects to a DiceDB server running on localhost at port 7379. If the connection fails, the application panics.
SendMessage
- Purpose: Sends a message to the DiceDB server, storing it as the "last_message". The message is formatted as "username:message".
- Parameters:
username
(string): The username of the sender.message
(string): The message content.
- Returns: None. It prints an error message to the console if the DiceDB command fails.
func SendMessage(username string, message string)
Subscribe
- Purpose: Subscribes to changes in the "last_message" key on the DiceDB server.
- Parameters: None
- Returns: None. It prints an error message to the console if the subscription fails.
func Subscribe()
ListenForMessages
- Purpose: Listens for message updates from the DiceDB server and calls the provided callback function (
onMessage
) with the new message. - Parameters:
onMessage
(func(message string)): A callback function that is called when a new message is received. The message content is passed as a string argument to this function.
- Returns: None. It continuously listens for messages until the channel is closed.
func ListenForMessages(onMessage func(message string))