u
This commit is contained in:
1 parent
c7a1f83c67
commit
6849579652
19 files changed
+600
-249
No files matched your search
@@ -1,5 +1,10 @@
|
||||
package mapx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// M 是 map[string]interface{} 的别名
|
||||
type M map[string]interface{}
|
||||
|
||||
@@ -29,6 +34,35 @@ func (m M) SetKV(kvs ...interface{}) M {
|
||||
return m
|
||||
}
|
||||
|
||||
// ---------------- 新增方法 ----------------
|
||||
|
||||
// SetIntToString 将 int 或 int64 直接转为 string 存储,用于前端安全传输
|
||||
func (m M) SetIntToString(key string, val interface{}) M {
|
||||
var s string
|
||||
switch v := val.(type) {
|
||||
case int:
|
||||
s = strconv.Itoa(v) // 直接转为 string
|
||||
case int64:
|
||||
s = strconv.FormatInt(v, 10)
|
||||
default:
|
||||
panic("SetIntToString: unsupported type")
|
||||
}
|
||||
m[key] = s
|
||||
return m
|
||||
}
|
||||
|
||||
// GetIntFromString 将前端传来的字符串解析为 int64
|
||||
func (m M) GetIntFromString(key string) int64 {
|
||||
if v, ok := m[key]; ok {
|
||||
if s, ok := v.(string); ok {
|
||||
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
|
||||
return i
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Get 获取值
|
||||
func (m M) Get(key string) interface{} {
|
||||
return m[key]
|
||||
@@ -62,44 +96,15 @@ func (m M) GetInt(key string) int {
|
||||
return int(val)
|
||||
case float64:
|
||||
return int(val)
|
||||
case string:
|
||||
if i, err := strconv.ParseInt(val, 10, 64); err == nil {
|
||||
return int(i)
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// GetFloat 获取浮点数类型
|
||||
func (m M) GetFloat(key string) float64 {
|
||||
if v, ok := m[key]; ok {
|
||||
switch val := v.(type) {
|
||||
case float32:
|
||||
return float64(val)
|
||||
case float64:
|
||||
return val
|
||||
case int:
|
||||
return float64(val)
|
||||
case int8:
|
||||
return float64(val)
|
||||
case int16:
|
||||
return float64(val)
|
||||
case int32:
|
||||
return float64(val)
|
||||
case int64:
|
||||
return float64(val)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// GetBool 获取布尔类型
|
||||
func (m M) GetBool(key string) bool {
|
||||
if v, ok := m[key]; ok {
|
||||
if b, ok := v.(bool); ok {
|
||||
return b
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Merge 合并另一个 M,后者会覆盖前者同名字段
|
||||
func (m M) Merge(other M) M {
|
||||
for k, v := range other {
|
||||
@@ -107,3 +112,8 @@ func (m M) Merge(other M) M {
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// MarshalJSON 支持 M 自定义 JSON 序列化
|
||||
func (m M) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(map[string]interface{}(m))
|
||||
}
|
||||
Reference in new issue
Block a user