Created
September 25, 2022 16:34
-
-
Save percybolmer/5c7bd26ba336f8f7b6df8b3d3ebda55d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NewMessageEvent is returned when responding to send_message | |
type NewMessageEvent struct { | |
SendMessageEvent | |
Sent time.Time `json:"sent"` | |
} | |
// SendMessageHandler will send out a message to all other participants in the chat | |
func SendMessageHandler(event Event, c *Client) error { | |
// Marshal Payload into wanted format | |
var chatevent SendMessageEvent | |
if err := json.Unmarshal(event.Payload, &chatevent); err != nil { | |
return fmt.Errorf("bad payload in request: %v", err) | |
} | |
// Prepare an Outgoing Message to others | |
var broadMessage NewMessageEvent | |
broadMessage.Sent = time.Now() | |
broadMessage.Message = chatevent.Message | |
broadMessage.From = chatevent.From | |
data, err := json.Marshal(broadMessage) | |
if err != nil { | |
return fmt.Errorf("failed to marshal broadcast message: %v", err) | |
} | |
// Place payload into an Event | |
var outgoingEvent Event | |
outgoingEvent.Payload = data | |
outgoingEvent.Type = EventNewMessage | |
// Broadcast to all other Clients | |
for client := range c.manager.clients { | |
client.egress <- outgoingEvent | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment