Files
workspace/code/base-project/base-go-v2/internal/utils/mapx/index.go
T
2025-11-05 22:25:09 +08:00

120 lines
2.2 KiB
Go

package mapx
import (
"encoding/json"
"strconv"
)
// M 是 map[string]interface{} 的别名
type M map[string]interface{}
// New 创建一个空 M
func New() M {
return M{}
}
// Set 设置单个键值,支持链式调用
func (m M) Set(key string, value interface{}) M {
m[key] = value
return m
}
// SetKV 批量设置键值,可变参数形式
func (m M) SetKV(kvs ...interface{}) M {
if len(kvs)%2 != 0 {
panic("SetKV 参数必须成对出现")
}
for i := 0; i < len(kvs); i += 2 {
key, ok := kvs[i].(string)
if !ok {
panic("SetKV 键必须是字符串")
}
m[key] = kvs[i+1]
}
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]
}
// GetString 获取字符串类型
func (m M) GetString(key string) string {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
// GetInt 获取整数类型
func (m M) GetInt(key string) int {
if v, ok := m[key]; ok {
switch val := v.(type) {
case int:
return val
case int8:
return int(val)
case int16:
return int(val)
case int32:
return int(val)
case int64:
return int(val)
case float32:
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
}
// Merge 合并另一个 M,后者会覆盖前者同名字段
func (m M) Merge(other M) M {
for k, v := range other {
m[k] = v
}
return m
}
// MarshalJSON 支持 M 自定义 JSON 序列化
func (m M) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}(m))
}