Server instances with multiple users

那年仲夏 提交于 2019-12-02 00:49:47
icza

Requests are served from multiple goroutines, concurrently. This means if they read/write the same variable, access to this variable must be synchronized.

Next, if you want a different instance of this data for each user, you may use a map, mapping from user ID or name to the data structure.

Let's assume the data structure is a struct, e.g.:

type customData struct {
    Field1 string
    Field2 int
    // Whatever fields you need
}

The map holding one for each user:

var userDataMap = map[string]customData{}

You may use a sync.RWMutex for protecting a map while it is read / written from a goroutine:

var mux = &sync.RWMutex{}

And synchronized access to the map, using the above mutex:

func Get(user string) customData {
    mux.RLock()
    defer mux.RUnlock()
    return userDataMap[user]
}

func Set(user string, data customData) {
    mux.Lock()
    userDataMap[user] = data
    mux.Unlock()
}

Another, more sophisticated solution would be to use server side HTTP sessions. For details, see Go session variables?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!