go实现安全并发map读写
2021-03-12 本文已影响0人
五岁小孩
参考
E:\svn\golang\pkg\mod\github.com\i!google-ink\gopay
代码实现
package gopay
import (
"encoding/json"
"encoding/xml"
"errors"
"io"
"sort"
"strings"
"sync"
)
type BodyMap map[string]interface{}
var mu sync.RWMutex
// 设置参数
func (bm BodyMap) Set(key string, value interface{}) {
mu.Lock()
bm[key] = value
mu.Unlock()
}
// 获取参数
func (bm BodyMap) Get(key string) string {
if bm == nil {
return NULL
}
mu.RLock()
defer mu.RUnlock()
value, ok := bm[key]
if !ok {
return NULL
}
v, ok := value.(string)
if !ok {
return convertToString(value)
}
return v
}
// 删除参数
func (bm BodyMap) Remove(key string) {
mu.Lock()
delete(bm, key)
mu.Unlock()
}