Server instances with multiple users

后端 未结 1 1808
我寻月下人不归
我寻月下人不归 2021-01-22 14:18

I\'m new to Go and I have the following problem. I tried to simplify it: I have a server which has for example a global variable myvar. All users can POST the endpo

相关标签:
1条回答
  • 2021-01-22 15:07

    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 mu = &sync.RWMutex{}
    

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

    func Get(user string) customData {
        mu.RLock()
        defer mu.RUnlock()
        return userDataMap[user]
    }
    
    func Set(user string, data customData) {
        mu.Lock()
        userDataMap[user] = data
        mu.Unlock()
    }
    

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

    0 讨论(0)
提交回复
热议问题