25 lines
401 B
Go
25 lines
401 B
Go
package util
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"sync"
|
|
)
|
|
|
|
type KeyedMutex struct{ m sync.Map }
|
|
|
|
func (k *KeyedMutex) Lock(key string) (unlock func()) {
|
|
v, _ := k.m.LoadOrStore(key, &sync.Mutex{})
|
|
mu := v.(*sync.Mutex)
|
|
mu.Lock()
|
|
return mu.Unlock
|
|
}
|
|
|
|
func RandomHex(n int) string {
|
|
b := make([]byte, n)
|
|
if _, err := rand.Read(b); err != nil {
|
|
panic(err)
|
|
}
|
|
return hex.EncodeToString(b)
|
|
}
|