title: Golang - lock per value
body: <p>I am writing a golang api that accepts a tableName value and a updEpoch value, ie:</p>
  <pre><code>curl -F &quot;tableName=abc&quot; -F &quot;updEpoch=123&quot; myhost:8080/singleroute
  curl -F &quot;tableName=abc&quot; -F &quot;updEpoch=456&quot; myhost:8080/singleroute
  curl -F &quot;tableName=def&quot; -F &quot;updEpoch=123&quot; myhost:8080/singleroute
  curl -F &quot;tableName=def&quot; -F &quot;updEpoch=345&quot; myhost:8080/singleroute
  </code></pre>
  <p>I want to allow multiple different tableName requests to be handled in parallel BUT only 1 request per tableName at the same time. So in above example, if above 4 requests fired at same time, then 1st and 3rd should be able to run at same time (as unique tableNames), but 2nd will only start once 1st finishes and 4th will only start once 3rd finishes. When I was researching mutex no example seemed to fit this case, I don't want to hardcode abc/def.etc anywhere in the code as same rule should apply to any arbitrary tableName.</p>
  <p>my guess based on Crowman's help:</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;sync&quot;
      &quot;time&quot;
      &quot;http&quot;
  )
  km := KeyedMutex{}
  type KeyedMutex struct {
      mutexes sync.Map // Zero value is empty and ready for use
  }
  
  func (m *KeyedMutex) Lock(key string) func() {
      value, _ := m.mutexes.LoadOrStore(key, &amp;sync.Mutex{})
      mtx := value.(*sync.Mutex)
      mtx.Lock()
  
      return func() { mtx.Unlock() }
  }
  
  func myFunc(key string, data string) string {
    //do some stuff
    return &quot;done for key:&quot;+key+&quot;, data: &quot;+data
  }
  
  func main() {
      key := //some form value sent to my api 
      data := //some form value sent to my api 
      unlock := km.Lock(key)
      defer unlock()
      retVal := myFunc(key, data)
  }
  </code></pre>