Files
go-socket/packages/cache/cache.go
T

86 lines
1.5 KiB
Go

package cache
import (
"fmt"
"sync"
"go-socket/packages/types"
"github.com/google/uuid"
)
var (
Mu sync.RWMutex
Users = make(map[uuid.UUID]*types.User)
)
func CacheGetUserById(id uuid.UUID) (*types.User, error) {
Mu.RLock()
defer Mu.RUnlock()
user, ok := Users[id]
if !ok {
return nil, fmt.Errorf("user %s not found", id)
}
return user, nil
}
func CacheGetUserByName(name string) (*types.User, error) {
Mu.RLock()
defer Mu.RUnlock()
for _, user := range Users {
if user.Name == name {
return user, nil
}
}
return nil, fmt.Errorf("user %s not found", name)
}
func CacheSaveUser(user *types.User) {
Mu.Lock()
defer Mu.Unlock()
Users[user.Id] = user
}
func CacheDeleteUser(id uuid.UUID) {
Mu.Lock()
defer Mu.Unlock()
delete(Users, id)
}
func CacheAddConnection(a, b *types.User, conn *types.Connection) {
first, second := a, b
if a.Id.String() > b.Id.String() {
first, second = b, a
}
first.Mu.Lock()
second.Mu.Lock()
a.Connections[conn.Id] = conn
b.Connections[conn.Id] = conn
second.Mu.Unlock()
first.Mu.Unlock()
}
func CacheDeleteConnection(a, b *types.User, id uuid.UUID) {
first, second := a, b
if a.Id.String() > b.Id.String() {
first, second = b, a
}
first.Mu.Lock()
second.Mu.Lock()
delete(a.Connections, id)
delete(b.Connections, id)
second.Mu.Unlock()
first.Mu.Unlock()
}
func CacheGetConnection(user *types.User, id uuid.UUID) (*types.Connection, bool) {
user.Mu.RLock()
defer user.Mu.RUnlock()
conn, ok := user.Connections[id]
return conn, ok
}