This commit is contained in:
oneao committed 2025-11-04 22:39:02 +08:00
1 parent 69d03709ba
commit 44fb48ef6a
9 files changed
+625 -25

No files matched your search

@@ -0,0 +1,109 @@
package mapx
// 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
}
// 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)
}
}
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 {
m[k] = v
}
return m
}
@@ -0,0 +1,42 @@
package validate
import (
"base-go-v2/internal/errs"
"errors"
"reflect"
"strings"
)
// ValidateNotEmpty 校验结构体中指定字段不能为空
func ValidateNotEmpty(s interface{}, fields ...string) error {
v := reflect.ValueOf(s)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
for _, field := range fields {
f := v.FieldByName(field)
if !f.IsValid() {
return errors.New("field " + field + " does not exist")
}
switch f.Kind() {
case reflect.String:
if strings.TrimSpace(f.String()) == "" {
return errs.NewValidationError(field, "不能为空")
}
case reflect.Slice, reflect.Array, reflect.Map:
if f.Len() == 0 {
return errs.NewValidationError(field, "不能为空")
}
case reflect.Ptr, reflect.Interface:
if f.IsNil() {
return errs.NewValidationError(field, "不能为空")
}
default:
continue
}
}
return nil
}