Sobes.tech
Junior — Middle

How do you implement a mechanism for determining a user's online status?

sobes.tech AI

Answer from AI

To implement a mechanism for determining a user's online status in Golang, several approaches can be used depending on the requirements for accuracy and scalability.

  1. Heartbeat from the client: The client periodically (e.g., every 30 seconds) sends a request to the server, updating the timestamp of the user's last activity. The server stores this timestamp (for example, in Redis or a database).

  2. Status determination: If less than a specified threshold (e.g., 1-2 minutes) has passed since the last update, the user is considered online; otherwise, offline.

  3. WebSocket: When using a WebSocket connection, the user can be considered online as long as the connection is active. When the connection is broken, the status changes to offline.

Example of simple status update using Redis:

import (
    "time"
    "github.com/go-redis/redis/v8"
    "context"
)

var ctx = context.Background()

func SetUserOnlineStatus(rdb *redis.Client, userID string) error {
    // Set key with TTL of 2 minutes
    return rdb.Set(ctx, "user_online_"+userID, "online", 2*time.Minute).Err()
}

func IsUserOnline(rdb *redis.Client, userID string) (bool, error) {
    val, err := rdb.Get(ctx, "user_online_"+userID).Result()
    if err == redis.Nil {
        return false, nil // key not found — offline
    } else if err != nil {
        return false, err
    }
    return val == "online", nil
}

Thus, the client should regularly call SetUserOnlineStatus to maintain the online status. The server checks for the presence of the key to determine the status.

How do you implement a mechanism for determining a… - sobes.tech