Skip to content

Commit

Permalink
modified response in case of sending status msg
Browse files Browse the repository at this point in the history
  • Loading branch information
mseltahir committed Oct 26, 2022
1 parent 2e260d9 commit 8a4536b
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 5 deletions.
2 changes: 1 addition & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
client.PreviousMessages()

// This will broadcast that this client is online to all users who have this client as a contact
client.ShareStatus()
client.ShareStatus("online")

// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
Expand Down
4 changes: 2 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,14 @@ func (c *Client) PreviousMessages() {

// ShareStatus will send `status` messages to all connected clients that have registered
// the current client as a contact.
func (c *Client) ShareStatus() {
func (c *Client) ShareStatus(status string) {
contacts, err := getContacts(c.ID, c.db)
if err == nil {
log.Printf("Contacts: %v", contacts)
for _, contact := range contacts {
if client, ok := c.hub.clients[contact]; ok {
log.Printf("Client is online: %v", client.ID)
client.conn.WriteJSON(Response{Status: c.ID})
client.conn.WriteJSON(Response{Status: StatusResponse{Mobile: c.ID, ConnectionStatus: status}})
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (h *Hub) Run() {
case client := <-h.unregister:
log.Printf("client ID: %s got disconnected", client.ID)
if _, ok := h.clients[client.ID]; ok {
client.ShareStatus()
client.ShareStatus("offline")
delete(h.clients, client.ID)
close(client.send)
}
Expand Down
9 changes: 8 additions & 1 deletion types.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ import (
"encoding/json"
)

// StatusResponse is the response send as part of Response in case we are sending
// a status (online/offline) message.
type StatusResponse struct {
Mobile string `json:"mobile,omitempty"`
ConnectionStatus string `json:"connection_status,omitempty"`
}

// Response is the object returned by the api in all cases.
type Response struct {
// Status will be null if we're sending chat messages
Status string `json:"status,omitempty"`
Status StatusResponse `json:"status,omitempty"`

// Messages will be null if we're sending status of a user
Messages []Message `json:"messages,omitempty"`
Expand Down

0 comments on commit 8a4536b

Please sign in to comment.