Compare commits

...

32 Commits

Author SHA1 Message Date
f363092a1a header key 信息增加cache-control 与 connection 2025-06-22 18:37:42 +08:00
cc17224cb9 order rule 增加 asc desc 枚举值 2025-04-25 10:47:26 +08:00
0b570213d5 逻辑升级后,修复单元测试 2025-04-20 18:14:47 +08:00
6df87081a4 优化 RedisCmd MarshalBinary 2025-04-20 18:13:56 +08:00
55e6ac5d83 RedisCmd 增加 MarshalBinary 实现, redis库序列化数据时, 演示实现此方法 2025-04-20 18:05:01 +08:00
3aba815bac Merge pull request '修复相关BUG + 增加单元测试, 覆盖率100%' (#3) from feature/upgrade into master
Reviewed-on: #3
2025-04-20 17:57:50 +08:00
fb1d6bb34f 修复相关BUG + 增加单元测试, 覆盖率100% 2025-04-20 17:57:01 +08:00
299edfcc9a 修复RedisCommand BUG + 增加单元测试 2025-04-20 13:40:39 +08:00
653843dc02 http 状态码增加499 2025-04-19 16:48:41 +08:00
d2ee86b14f HttpCode增加Value字段 2025-04-19 13:45:49 +08:00
89d1d110dd 增加http code 枚举值定义 2025-04-19 13:11:46 +08:00
2de82c68e2 validator交眼规则枚举值支持omitempty 2025-04-17 15:28:45 +08:00
7e4a6f9f14 更新header key 定义 2025-03-28 12:03:04 +08:00
d6e86b64f7 增加获取各种数据类型的默认值方法 2025-03-21 18:22:41 +08:00
734d9a9f77 增加获取各种数据类型的默认值方法 2025-03-21 18:15:44 +08:00
1aad276c88 细化int/uint/float数据类型定义 2025-03-21 17:11:21 +08:00
863c03f34b MimiType增加text/plain 2025-02-27 12:05:46 +08:00
f17dd21cbd request data location 支持any 2025-02-26 21:15:48 +08:00
8232f587a6 update http header 2025-02-15 22:17:18 +08:00
2155b7ab1e update log level 2025-02-15 22:16:11 +08:00
a50062af46 update request data location 2025-02-08 10:03:30 +08:00
330777d805 swagger版本定义: 2.0.0 => 2.0 2025-02-07 21:20:05 +08:00
67b5d5cc61 fix htp scheme 2025-02-07 21:00:30 +08:00
b75d2ec7f3 fix data type enum 2025-02-07 20:56:48 +08:00
8ebc73a0df Merge pull request '增加验证规则的枚举值' (#2) from feature/validator into master
Reviewed-on: #2
2025-02-07 20:52:03 +08:00
5d23a5428f 增加 ValidatorRule.IsValid 方法 2025-01-24 18:44:01 +08:00
d0dbba0156 修复ValidatorRule.String方法NPE异常 2025-01-24 15:58:04 +08:00
18dd06b515 优化验证规则配置,增加更多属性 2025-01-24 15:20:35 +08:00
33c60bcd2d 完善validator枚举值验证 2025-01-24 15:05:46 +08:00
bd95270130 优化常量定义 2025-01-24 12:35:16 +08:00
18ceef4276 增加内置验证规则枚举值 2025-01-23 18:40:04 +08:00
bcc527dccc 增加验证规则的枚举值 2025-01-22 17:53:00 +08:00
25 changed files with 1638 additions and 106 deletions

View File

@ -14,12 +14,12 @@ package consts
// Date : 14:10 2024/11/25
type DataType string
func (df *DataType) String() string {
return string(*df)
func (df DataType) String() string {
return string(df)
}
func (df *DataType) MarshalJSON() ([]byte, error) {
return []byte(df.String()), nil
func (df DataType) MarshalJSON() ([]byte, error) {
return []byte(`"` + df.String() + `"`), nil
}
// IsValid 判断枚举值是否有效
@ -27,22 +27,31 @@ func (df *DataType) MarshalJSON() ([]byte, error) {
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:45 2024/11/25
func (df *DataType) IsValid() bool {
func (df DataType) IsValid() bool {
for _, item := range DataTypeList {
if item.Value == *df {
if item.Value == df || item.Value.String() == df.String() {
return true
}
}
return false
}
const (
var (
DataTypeUnknown DataType = "unknown" // 位置数据类型
DataTypeNil DataType = "nil" // nil
DataTypePtr DataType = "ptr" // 指针
DataTypeInt DataType = "int" // int类型 -> int64
DataTypeInt8 DataType = "int8" // int8类型
DataTypeInt16 DataType = "int16" // int16类型
DataTypeInt32 DataType = "int32" // int32类型
DataTypeInt64 DataType = "int64" // int64类型
DataTypeUint DataType = "uint" // uint类型 -> uint64
DataTypeFloat DataType = "float" // float类型 -> float64
DataTypeUint8 DataType = "uint8" // uint8类型
DataTypeUint16 DataType = "uint16" // uint16类型
DataTypeUint32 DataType = "uint32" // uint32类型
DataTypeUint64 DataType = "uint64" // uint64类型
DataTypeFloat32 DataType = "float32" // float32类型
DataTypeFloat64 DataType = "float64" // float64类型
DataTypeBool DataType = "bool" // bool类型
DataTypeString DataType = "string" // 字符串类型
DataTypeSliceAny DataType = "[]any" // any数组 -> []any
@ -67,7 +76,7 @@ const (
DataTypeSliceMapAnyAny DataType = "[]map[any]any" // 字符串数组 -> []map[any]any, slice对象
DataTypeSliceMapAnyAnyWithMarshal DataType = "[]map[any]any_marshal" // 字符串数组 -> []map[any]any, json序列化后的结果
DataTypeSliceMapStringAny DataType = "[]map[string]any" // 字符串数组 -> map[string]any, slice对象
DataTypeSliceMapStringAnyWithMarshal = "[]map[string]any_marshal" // 字符串数组 -> []map[string]any, slice对象, json序列化之后的结果
DataTypeSliceMapStringAnyWithMarshal DataType = "[]map[string]any_marshal" // 字符串数组 -> []map[string]any, slice对象, json序列化之后的结果
DataTypeMapStrInt DataType = "map[string]int" // map -> map[string]int64
DataTypeMapStrIntWithMarshal DataType = "map[string]int_marshal" // map -> map[string]int64,json序列化之后的结果
DataTypeMapStrUint DataType = "map[string]uint" // map -> map[string]uint64
@ -87,8 +96,17 @@ const (
DataTypeAny DataType = "any" // 任意类型 -> any
DataTypeStringPtr DataType = "string_ptr" // *string, 字符串指针
DataTypeIntPtr DataType = "int_ptr" // *int64, int64指针
DataTypeInt8Ptr DataType = "int8_ptr" // *int8, int8指针
DataTypeInt16Ptr DataType = "int16_ptr" // *int16, int16指针
DataTypeInt32Ptr DataType = "int32_ptr" // *int32, int32指针
DataTypeInt64Ptr DataType = "int64_ptr" // *int64, int64指针
DataTypeUintPtr DataType = "uint_ptr" // *uint64, uint64指针
DataTypeFloatPtr DataType = "float_ptr" // *float64, float64指针
DataTypeUint8Ptr DataType = "uint8_ptr" // *uint8, uint8指针
DataTypeUint16Ptr DataType = "uint16_ptr" // *uint16, uint16指针
DataTypeUint32Ptr DataType = "uint32_ptr" // *uint32, uint32指针
DataTypeUint64Ptr DataType = "uint64_ptr" // *uint64, uint64指针
DataTypeFloat32Ptr DataType = "float32_ptr" // *float32, float32指针
DataTypeFloat64Ptr DataType = "float64_ptr" // *float64, float64指针
DataTypeBoolPtr DataType = "bool_ptr" // *bool, 字符串指针
)
@ -125,9 +143,18 @@ var (
DataTypeList = []DataTypeDesc{
// 基础数据类型
getDataTypeDesc(DataTypeAny, "任意数据类型"),
getDataTypeDesc(DataTypeInt, "int类型 -> int64"),
getDataTypeDesc(DataTypeUint, "uint类型 -> uint64"),
getDataTypeDesc(DataTypeFloat, "float类型 -> float64"),
getDataTypeDesc(DataTypeInt, "int类型"),
getDataTypeDesc(DataTypeInt8, "int8类型"),
getDataTypeDesc(DataTypeInt16, "int16类型"),
getDataTypeDesc(DataTypeInt32, "int32类型"),
getDataTypeDesc(DataTypeInt64, "int64类型"),
getDataTypeDesc(DataTypeUint, "uint类型"),
getDataTypeDesc(DataTypeUint8, "uint8类型"),
getDataTypeDesc(DataTypeUint16, "uint16类型"),
getDataTypeDesc(DataTypeUint32, "uint32类型"),
getDataTypeDesc(DataTypeUint64, "uint64类型"),
getDataTypeDesc(DataTypeFloat32, "float32类型"),
getDataTypeDesc(DataTypeFloat64, "float64类型"),
getDataTypeDesc(DataTypeBool, "bool类型"),
getDataTypeDesc(DataTypeString, "字符串类型"),
@ -176,9 +203,18 @@ var (
// 基础类型的指针类型
getDataTypeDesc(DataTypeStringPtr, "*string, 字符串指针"),
getDataTypeDesc(DataTypeUintPtr, "*int64, int64指针"),
getDataTypeDesc(DataTypeIntPtr, "*int64, *uint64, uint64指针"),
getDataTypeDesc(DataTypeFloatPtr, "*float64, float64指针"),
getDataTypeDesc(DataTypeUintPtr, "*uint, uint指针"),
getDataTypeDesc(DataTypeUintPtr, "*uint8, uint8指针"),
getDataTypeDesc(DataTypeUintPtr, "*uint16, uint16指针"),
getDataTypeDesc(DataTypeUintPtr, "*uint32, uint32指针"),
getDataTypeDesc(DataTypeUintPtr, "*uint64, uint64指针"),
getDataTypeDesc(DataTypeIntPtr, "*int, int指针"),
getDataTypeDesc(DataTypeIntPtr, "*int8, int8指针"),
getDataTypeDesc(DataTypeIntPtr, "*int16, int16指针"),
getDataTypeDesc(DataTypeIntPtr, "*int32, int32指针"),
getDataTypeDesc(DataTypeIntPtr, "*int64, int64指针"),
getDataTypeDesc(DataTypeFloat32Ptr, "*float32, float32指针"),
getDataTypeDesc(DataTypeFloat32Ptr, "*float64, float64指针"),
getDataTypeDesc(DataTypeBoolPtr, "*bool, 字符串指针"),
}
)
@ -194,3 +230,203 @@ func getDataTypeDesc(value DataType, description string) DataTypeDesc {
Description: description,
}
}
var (
// DataTypeBaseNumber 基础的int类型
DataTypeBaseNumber = []DataType{
DataTypeInt, DataTypeInt8, DataTypeInt16, DataTypeInt32, DataTypeInt64,
DataTypeUint, DataTypeUint8, DataTypeUint16, DataTypeUint32, DataTypeUint64,
DataTypeFloat32, DataTypeFloat64,
DataTypeIntPtr, DataTypeInt8Ptr, DataTypeInt16Ptr, DataTypeInt32Ptr, DataTypeInt64Ptr,
DataTypeUintPtr, DataTypeUint8Ptr, DataTypeUint16Ptr, DataTypeUint32Ptr, DataTypeUint64Ptr,
DataTypeFloat32Ptr, DataTypeFloat64Ptr,
}
DataTypeBaseInt = []DataType{
DataTypeInt, DataTypeInt8, DataTypeInt16, DataTypeInt32, DataTypeInt64,
DataTypeIntPtr, DataTypeInt8Ptr, DataTypeInt16Ptr, DataTypeInt32Ptr, DataTypeInt64Ptr,
}
DataTypeBaseUint = []DataType{
DataTypeUint, DataTypeUint8, DataTypeUint16, DataTypeUint32, DataTypeUint64,
DataTypeUintPtr, DataTypeUint8Ptr, DataTypeUint16Ptr, DataTypeUint32Ptr, DataTypeUint64Ptr,
}
DataTypeBaseFloat = []DataType{DataTypeFloat32, DataTypeFloat64, DataTypeFloat32Ptr, DataTypeFloat64Ptr}
DataTypeBaseString = []DataType{DataTypeString, DataTypeStringPtr}
DataTypeBaseBool = []DataType{DataTypeBool, DataTypeBoolPtr}
DataTypeSliceMarshal = []DataType{
DataTypeSliceAnyWithMarshal,
DataTypeSliceIntWithMarshal,
DataTypeSliceUintWithMarshal,
DataTypeSliceFloatWithMarshal,
DataTypeSliceBoolWithMarshal,
DataTypeSliceMapAnyAnyWithMarshal,
DataTypeSliceMapStringAnyWithMarshal,
DataTypeSliceAnyWithMarshal,
DataTypeSliceSliceWithMarshal,
}
DataTypeSliceSplit = []DataType{
DataTypeSliceIntWithChar,
DataTypeSliceUintWithChar,
DataTypeSliceFloatWithChar,
DataTypeSliceBoolWithChar,
DataTypeSliceStringWithChar,
}
DataTypeSlice = []DataType{
DataTypeSliceString,
DataTypeSliceAny,
DataTypeSliceBool,
DataTypeSliceMapStringAny,
DataTypeSliceInt,
DataTypeSliceUint,
DataTypeSliceFloat,
DataTypeSliceMapAnyAny,
DataTypeSliceSlice,
}
DataTypeMap = []DataType{
DataTypeMapStrAny,
DataTypeMapAnyAny,
DataTypeMapStrBool,
DataTypeMapStrInt,
DataTypeMapStrFloat,
DataTypeMapStrUint,
DataTypeMapStrSlice,
DataTypeMapStrStr,
}
DataTypeMapMarshal = []DataType{
DataTypeMapStrAnyWithMarshal,
DataTypeMapAnyAnyWithMarshal,
DataTypeMapStrBoolWithMarshal,
DataTypeMapStrIntWithMarshal,
DataTypeMapStrFloatWithMarshal,
DataTypeMapStrUintWithMarshal,
DataTypeMapStrSliceWithMarshal,
DataTypeMapStrStrWithMarshal,
}
)
func getMergeDataTypeList(dataTypeList ...[]DataType) []DataType {
res := []DataType{}
for _, dataTypeItemList := range dataTypeList {
res = append(res, dataTypeItemList...)
}
return res
}
// GetDataTypeDefaultValue 获取不同类型的默认值
func GetDataTypeDefaultValue(dataType DataType) any {
switch dataType {
case DataTypeInt:
return int(0)
case DataTypeInt8:
return int8(0)
case DataTypeInt16:
return int16(0)
case DataTypeInt32:
return int32(0)
case DataTypeInt64:
return int64(0)
case DataTypeUint:
return uint(0)
case DataTypeUint8:
return uint8(0)
case DataTypeUint16:
return uint16(0)
case DataTypeUint32:
return uint32(0)
case DataTypeUint64:
return uint64(0)
case DataTypeFloat32:
return float32(0)
case DataTypeFloat64:
return float64(0)
case DataTypeBool:
return false
case DataTypeString:
return ""
case DataTypeIntPtr:
return new(int)
case DataTypeInt8Ptr:
return new(int8)
case DataTypeInt16Ptr:
return new(int16)
case DataTypeInt32Ptr:
return new(int32)
case DataTypeInt64Ptr:
return new(int64)
case DataTypeUintPtr:
return new(uint)
case DataTypeUint8Ptr:
return new(uint8)
case DataTypeUint16Ptr:
return new(uint16)
case DataTypeUint32Ptr:
return new(uint32)
case DataTypeUint64Ptr:
return new(uint64)
case DataTypeFloat32Ptr:
return new(float32)
case DataTypeFloat64Ptr:
return new(float64)
case DataTypeBoolPtr:
return new(bool)
case DataTypeMapStrAny:
return map[string]any{}
case DataTypeMapAnyAny:
return map[any]any{}
case DataTypeMapStrBool:
return map[string]bool{}
case DataTypeMapStrInt:
return map[string]int{}
case DataTypeMapStrFloat:
return map[string]float64{}
case DataTypeMapStrUint:
return map[string]uint{}
case DataTypeMapStrSlice:
return map[string][]any{}
case DataTypeMapStrStr:
return map[string]string{}
case DataTypeSliceAny:
return []any{}
case DataTypeSliceString:
return []string{}
case DataTypeSliceBool:
return []bool{}
case DataTypeSliceInt:
return []int{}
case DataTypeSliceUint:
return []uint{}
case DataTypeSliceFloat:
return []float64{}
case DataTypeSliceMapAnyAny:
// map[any]any 序列化会有问题,当做 map[string]any 处理
return []map[string]any{}
case DataTypeSliceMapStringAny:
return []map[string]any{}
default:
// 序列化之后的map
for _, dataTypeItem := range DataTypeMapMarshal {
if dataTypeItem == dataType {
return "{}"
}
}
// 序列化之后的slice
for _, dataTypeItem := range DataTypeSliceMarshal {
if dataTypeItem == dataType {
return "[]"
}
}
// 指定分隔符分割的slice
for _, dataTypeItem := range DataTypeSliceSplit {
if dataTypeItem == dataType {
return ""
}
}
// 未枚举的slice类型用any接收
for _, dataTypeItem := range DataTypeSlice {
if dataTypeItem == dataType {
return []any{}
}
}
}
// 未枚举的一律用any接收
return *new(any)
}

188
data_type_test.go Normal file
View File

@ -0,0 +1,188 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 15:06
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestDataType_String(t *testing.T) {
Convey("data type 字符串值", t, func() {
byteData, err := json.Marshal(DataTypeString)
So(err, ShouldBeNil)
So(DataTypeString.String(), ShouldEqual, "string")
So(string(byteData), ShouldEqual, `"string"`)
})
Convey("data type MarshalJSON", t, func() {
str, err := DataTypeString.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"string"`)
dataList := []DataType{DataTypeString}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["string"]`)
})
}
func TestDataType_IsValid(t *testing.T) {
Convey("data type 非法验证", t, func() {
So(DataType("Invalid").IsValid(), ShouldBeFalse)
})
Convey("data type 合法验证", t, func() {
So(DataType("string").IsValid(), ShouldBeTrue)
})
}
func TestGetDataTypeDefaultValue(t *testing.T) {
Convey("int 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt), ShouldEqual, 0)
})
Convey("int8 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt8), ShouldEqual, int8(0))
})
Convey("int16 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt16), ShouldEqual, int16(0))
})
Convey("int32 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt32), ShouldEqual, int32(0))
})
Convey("int64 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt64), ShouldEqual, int64(0))
})
Convey("uint 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint), ShouldEqual, uint(0))
})
Convey("uint8 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint8), ShouldEqual, uint8(0))
})
Convey("uint16 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint16), ShouldEqual, uint16(0))
})
Convey("uint32 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint32), ShouldEqual, uint32(0))
})
Convey("uint64 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint64), ShouldEqual, uint64(0))
})
Convey("float32 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeFloat32), ShouldEqual, float32(0))
})
Convey("uint64 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeFloat64), ShouldEqual, float64(0))
})
Convey("bool 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeBool), ShouldBeFalse)
})
Convey("string 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeString), ShouldBeEmpty)
})
Convey("IntPtr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeIntPtr), ShouldEqual, new(int))
})
Convey("Int8Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt8Ptr), ShouldEqual, new(int8))
})
Convey("Int16Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt16Ptr), ShouldEqual, new(int16))
})
Convey("Int32Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt32Ptr), ShouldEqual, new(int32))
})
Convey("Int64Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeInt64Ptr), ShouldEqual, new(int64))
})
Convey("UintPtr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUintPtr), ShouldEqual, new(uint))
})
Convey("Uint8Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint8Ptr), ShouldEqual, new(uint8))
})
Convey("Uint16Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint16Ptr), ShouldEqual, new(uint16))
})
Convey("Uint32Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint32Ptr), ShouldEqual, new(uint32))
})
Convey("Uint64Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeUint64Ptr), ShouldEqual, new(uint64))
})
Convey("Float32Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeFloat32Ptr), ShouldEqual, new(float32))
})
Convey("Float64Ptr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeFloat64Ptr), ShouldEqual, new(float64))
})
Convey("BoolPtr 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeBoolPtr), ShouldEqual, new(bool))
})
Convey("map[string]any 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrAny), ShouldEqual, map[string]any{})
})
Convey("map[any]any 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapAnyAny), ShouldEqual, map[any]any{})
})
Convey("map[string]bool 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrBool), ShouldEqual, map[string]bool{})
})
Convey("map[string]int 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrInt), ShouldEqual, map[string]int{})
})
Convey("map[string]float 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrFloat), ShouldEqual, map[string]float64{})
})
Convey("map[string]uint 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrUint), ShouldEqual, map[string]uint{})
})
Convey("map[string]slice 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrSlice), ShouldEqual, map[string][]any{})
})
Convey("map[string]string 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrStr), ShouldEqual, map[string]string{})
})
Convey("[]any 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceAny), ShouldEqual, []any{})
})
Convey("[]string 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceString), ShouldEqual, []string{})
})
Convey("[]bool 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceBool), ShouldEqual, []bool{})
})
Convey("[]int 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceInt), ShouldEqual, []int{})
})
Convey("[]uint 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceUint), ShouldEqual, []uint{})
})
Convey("[]float 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceFloat), ShouldEqual, []float64{})
})
Convey("[]map[string]any 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceMapStringAny), ShouldEqual, []map[string]any{})
})
Convey("[]map[any]any 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceMapAnyAny), ShouldEqual, []map[string]any{})
})
Convey("map marshal 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeMapStrAnyWithMarshal), ShouldEqual, "{}")
})
Convey("slice marshal 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceBoolWithMarshal), ShouldEqual, "[]")
})
Convey("slice split 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceIntWithChar), ShouldEqual, "")
})
Convey("未枚举的alice 默认值", t, func() {
So(GetDataTypeDefaultValue(DataTypeSliceSlice), ShouldEqual, []any{})
})
Convey("unknown 默认值", t, func() {
So(GetDataTypeDefaultValue(DataType("unknown")), ShouldEqual, nil)
})
}

View File

@ -30,3 +30,8 @@ const (
WhereOperateLike = "like" // like
WhereOperateNotLike = "not_like" // not like
)
const (
OrderRuleAsc = "asc" // 升序
OrderRuleDesc = "desc" // 降序
)

View File

@ -1,8 +0,0 @@
// Package enums ...
//
// Description : enums ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-25 14:39
package enums

View File

@ -1,8 +0,0 @@
// Package enums ...
//
// Description : enums ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-25 14:08
package enums

View File

@ -9,26 +9,17 @@ package consts
type FileType string
func (ft *FileType) String() string {
return string(*ft)
func (ft FileType) String() string {
return string(ft)
}
func (ft *FileType) MarshalJSON() ([]byte, error) {
return []byte(ft.String()), nil
func (ft FileType) MarshalJSON() ([]byte, error) {
return []byte(`"` + ft.String() + `"`), nil
}
func (ft *FileType) IsValid() bool {
supportFileTypeList := []FileType{
FileTypeJson,
FileTypeIni,
FileTypeYml,
FileTypeYaml,
FileTypeToml,
FileTypeXml,
FileTypeTxt,
}
for _, fileType := range supportFileTypeList {
if fileType == *ft {
func (ft FileType) IsValid() bool {
for _, fileType := range SupportFileTypeList {
if fileType.Value == ft || fileType.Value.String() == ft.String() {
return true
}
}
@ -45,3 +36,41 @@ const (
FileTypeTxt FileType = "txt" // txt格式文件
FileTypeUnknown FileType = "unknown" // 未知格式
)
type FileTypeDesc struct {
Value FileType
Desc string
}
var (
SupportFileTypeList = []FileTypeDesc{
{
Value: FileTypeJson,
Desc: "json格式文件",
},
{
Value: FileTypeIni,
Desc: "init格式文件",
},
{
Value: FileTypeYml,
Desc: "yml格式文件",
},
{
Value: FileTypeYaml,
Desc: "yaml格式文件",
},
{
Value: FileTypeToml,
Desc: "toml格式文件",
},
{
Value: FileTypeTxt,
Desc: "txt格式文件",
},
{
Value: FileTypeXml,
Desc: "xml格式文件",
},
}
)

41
file_type_test.go Normal file
View File

@ -0,0 +1,41 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 15:17
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestFileType_String(t *testing.T) {
Convey("file type 字符串值", t, func() {
byteData, err := json.Marshal(FileTypeJson)
So(err, ShouldBeNil)
So(FileTypeJson.String(), ShouldEqual, "json")
So(string(byteData), ShouldEqual, `"json"`)
})
Convey("file type MarshalJSON", t, func() {
str, err := FileTypeJson.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"json"`)
dataList := []FileType{FileTypeJson}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["json"]`)
})
}
func TestFileType_IsValid(t *testing.T) {
Convey("file type 非法验证", t, func() {
So(FileType("Invalid").IsValid(), ShouldBeFalse)
})
Convey("file type 合法验证", t, func() {
So(FileType("json").IsValid(), ShouldBeTrue)
})
}

12
go.mod
View File

@ -1,3 +1,13 @@
module git.zhangdeman.cn/zhangdeman/consts
go 1.19
go 1.23.0
toolchain go1.24.2
require github.com/smartystreets/goconvey v1.8.1
require (
github.com/gopherjs/gopherjs v1.17.2 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/smarty/assertions v1.15.0 // indirect
)

8
go.sum Normal file
View File

@ -0,0 +1,8 @@
github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g=
github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY=
github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec=
github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY=
github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60=

View File

@ -9,12 +9,12 @@ package consts
type HttpHeader string
func (hh *HttpHeader) String() string {
return string(*hh)
func (hh HttpHeader) String() string {
return string(hh)
}
func (hh *HttpHeader) MarshalJSON() ([]byte, error) {
return []byte(hh.String()), nil
func (hh HttpHeader) MarshalJSON() ([]byte, error) {
return []byte(`"` + hh.String() + `"`), nil
}
const (
@ -24,3 +24,18 @@ const (
HeaderKeyAccessControlExposeHeaders HttpHeader = "Access-Control-Expose-Headers" // 允许浏览器端能够获取相应的header值
HeaderKeyAccessControlMaxAge HttpHeader = "Access-Control-Max-Age" // 控制发送预检请求options的频率单位 : 秒
)
const (
HeaderKeyContentType HttpHeader = "Content-Type" // 请求头中Content-Type的key
HeaderKeyCacheControl HttpHeader = "Cache-Control" // 禁用缓存
HeaderKeyConnection HttpHeader = "Connection" // 连接信息
HeaderKeyReferer HttpHeader = "Referer" // 请求头中Referer的key
HeaderKeyUserAgent HttpHeader = "User-Agent" // 请求头中User-Agent的key
HeaderKeyAccept HttpHeader = "Accept" // accept
HeaderKeyAcceptEncoding HttpHeader = "Accept-Encoding" // accept-encoding
HeaderKeyAcceptLanguage HttpHeader = "Accept-Language" // accept-language
HeaderKeyAuthorization HttpHeader = "Authorization" // authorization
HeaderKeyCookie HttpHeader = "Cookie" // cookie
HeaderKeyOrigin HttpHeader = "Origin" // origin
HeaderKeyHost HttpHeader = "Host" // host
)

32
header_test.go Normal file
View File

@ -0,0 +1,32 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 14:22
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestHttpHeader_String(t *testing.T) {
Convey("http header字符串值", t, func() {
byteData, err := json.Marshal(HeaderKeyContentType)
So(err, ShouldBeNil)
So(HeaderKeyContentType.String(), ShouldEqual, "Content-Type")
So(string(byteData), ShouldEqual, `"Content-Type"`)
})
Convey("http header MarshalJSON", t, func() {
str, err := HeaderKeyContentType.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"Content-Type"`)
dataList := []HttpHeader{HeaderKeyContentType}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["Content-Type"]`)
})
}

112
http_code.go Normal file
View File

@ -0,0 +1,112 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-19 12:38
package consts
import (
"fmt"
"net/http"
)
type HttpCode struct {
Value any `json:"value"`
Code int `json:"code"`
Desc string `json:"desc"`
}
func newHttpCodeData(httpCode int) HttpCode {
desc := http.StatusText(httpCode)
if len(desc) == 0 {
if httpCode == 499 {
desc = "client request timeout"
} else {
desc = fmt.Sprintf("%v: unknown error", httpCode)
}
}
return HttpCode{
Value: httpCode,
Code: httpCode,
Desc: desc,
}
}
var (
HttpCodeList = []HttpCode{
// 1xx
newHttpCodeData(http.StatusContinue),
newHttpCodeData(http.StatusSwitchingProtocols),
newHttpCodeData(http.StatusProcessing),
newHttpCodeData(http.StatusEarlyHints),
// 2xx
newHttpCodeData(http.StatusOK),
newHttpCodeData(http.StatusCreated),
newHttpCodeData(http.StatusAccepted),
newHttpCodeData(http.StatusNonAuthoritativeInfo),
newHttpCodeData(http.StatusNoContent),
newHttpCodeData(http.StatusResetContent),
newHttpCodeData(http.StatusPartialContent),
newHttpCodeData(http.StatusMultiStatus),
newHttpCodeData(http.StatusAlreadyReported),
newHttpCodeData(http.StatusIMUsed),
// 3xx
newHttpCodeData(http.StatusMultipleChoices),
newHttpCodeData(http.StatusMovedPermanently),
newHttpCodeData(http.StatusFound),
newHttpCodeData(http.StatusSeeOther),
newHttpCodeData(http.StatusNotModified),
newHttpCodeData(http.StatusUseProxy),
newHttpCodeData(http.StatusTemporaryRedirect),
newHttpCodeData(http.StatusPermanentRedirect),
// 4xx
newHttpCodeData(http.StatusBadRequest),
newHttpCodeData(http.StatusUnauthorized),
newHttpCodeData(http.StatusPaymentRequired),
newHttpCodeData(http.StatusForbidden),
newHttpCodeData(http.StatusNotFound),
newHttpCodeData(http.StatusMethodNotAllowed),
newHttpCodeData(http.StatusNotAcceptable),
newHttpCodeData(http.StatusProxyAuthRequired),
newHttpCodeData(http.StatusRequestTimeout),
newHttpCodeData(http.StatusConflict),
newHttpCodeData(http.StatusGone),
newHttpCodeData(http.StatusLengthRequired),
newHttpCodeData(http.StatusPreconditionFailed),
newHttpCodeData(http.StatusRequestEntityTooLarge),
newHttpCodeData(http.StatusRequestURITooLong),
newHttpCodeData(http.StatusUnsupportedMediaType),
newHttpCodeData(http.StatusRequestedRangeNotSatisfiable),
newHttpCodeData(http.StatusExpectationFailed),
newHttpCodeData(http.StatusTeapot),
newHttpCodeData(http.StatusMisdirectedRequest),
newHttpCodeData(http.StatusUnprocessableEntity),
newHttpCodeData(http.StatusLocked),
newHttpCodeData(http.StatusFailedDependency),
newHttpCodeData(http.StatusTooEarly),
newHttpCodeData(http.StatusUpgradeRequired),
newHttpCodeData(http.StatusPreconditionRequired),
newHttpCodeData(http.StatusTooManyRequests),
newHttpCodeData(http.StatusRequestHeaderFieldsTooLarge),
newHttpCodeData(http.StatusUnavailableForLegalReasons),
newHttpCodeData(499),
// 5xx
newHttpCodeData(http.StatusInternalServerError),
newHttpCodeData(http.StatusNotImplemented),
newHttpCodeData(http.StatusBadGateway),
newHttpCodeData(http.StatusServiceUnavailable),
newHttpCodeData(http.StatusGatewayTimeout),
newHttpCodeData(http.StatusHTTPVersionNotSupported),
newHttpCodeData(http.StatusVariantAlsoNegotiates),
newHttpCodeData(http.StatusInsufficientStorage),
newHttpCodeData(http.StatusLoopDetected),
newHttpCodeData(http.StatusNotExtended),
newHttpCodeData(http.StatusNetworkAuthenticationRequired),
}
)

27
http_code_test.go Normal file
View File

@ -0,0 +1,27 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 15:29
package consts
import (
. "github.com/smartystreets/goconvey/convey"
"strings"
"testing"
)
func Test_newHttpCodeData(t *testing.T) {
Convey("newHttpCode 验证", t, func() {
hCode := newHttpCodeData(499)
So(hCode.Code, ShouldEqual, 499)
So(hCode.Desc, ShouldEqual, "client request timeout")
So(hCode.Value, ShouldEqual, 499)
hCode = newHttpCodeData(4990)
So(hCode.Code, ShouldEqual, 4990)
So(strings.Contains(hCode.Desc, "unknown error"), ShouldBeTrue)
So(hCode.Value, ShouldEqual, 4990)
})
}

View File

@ -9,15 +9,15 @@ package consts
type LogLevel string
func (ll *LogLevel) String() string {
return string(*ll)
func (ll LogLevel) String() string {
return string(ll)
}
func (ll *LogLevel) MarshalJSON() ([]byte, error) {
return []byte(ll.String()), nil
func (ll LogLevel) MarshalJSON() ([]byte, error) {
return []byte(`"` + ll.String() + `"`), nil
}
func (ll *LogLevel) IsValid() bool {
func (ll LogLevel) IsValid() bool {
levelList := []LogLevel{
LogLevelDebug,
LogLevelInfo,
@ -26,7 +26,7 @@ func (ll *LogLevel) IsValid() bool {
LogLevelPanic,
}
for _, level := range levelList {
if level == *ll {
if level == ll {
return true
}
}
@ -47,18 +47,12 @@ func (ls LogSplit) String() string {
return string(ls)
}
func (ls LogSplit) MarshalJSON() ([]byte, error) {
return []byte(ls.String()), nil
return []byte(`"` + ls.String() + `"`), nil
}
func (ls LogSplit) IsValid() bool {
supportSplitList := []LogSplit{
LogSplitHour,
LogSplitDay,
LogSplitMonth,
LogSplitYear,
}
for _, supportSplit := range supportSplitList {
if supportSplit == ls {
for _, supportSplit := range SupportLogSplitList {
if supportSplit.Value == ls || supportSplit.Value.String() == ls.String() {
return true
}
}
@ -72,6 +66,32 @@ const (
LogSplitYear LogSplit = "YEAR"
)
type LogSplitDesc struct {
Value LogSplit `json:"value"`
Desc string `json:"desc"`
}
var (
SupportLogSplitList = []LogSplitDesc{
{
Value: LogSplitHour,
Desc: "按小时切割",
},
{
Value: LogSplitDay,
Desc: "按天切割",
},
{
Value: LogSplitMonth,
Desc: "按月切割",
},
{
Value: LogSplitYear,
Desc: "按年切割",
},
}
)
const (
LogPathDefault = "logs"
)

View File

@ -9,11 +9,60 @@ package consts
import (
"encoding/json"
"fmt"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestLogLevel_String(t *testing.T) {
Convey("logger type字符串值", t, func() {
byteData, err := json.Marshal(LogLevelDebug)
fmt.Println(string(byteData), err)
So(err, ShouldBeNil)
So(LogLevelDebug.String(), ShouldEqual, "DEBUG")
So(string(byteData), ShouldEqual, `"DEBUG"`)
})
Convey("logger type MarshalJSON", t, func() {
str, err := LogLevelDebug.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"DEBUG"`)
dataList := []LogLevel{LogLevelDebug}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["DEBUG"]`)
})
}
func TestLogLevel_IsValid(t *testing.T) {
Convey("logger type 非法验证", t, func() {
So(LogLevel("Invalid").IsValid(), ShouldBeFalse)
})
Convey("logger type 合法验证", t, func() {
So(LogLevelDebug.IsValid(), ShouldBeTrue)
})
}
func TestLogSplit_String(t *testing.T) {
Convey("logger split 字符串值", t, func() {
byteData, err := json.Marshal(LogSplitHour)
So(err, ShouldBeNil)
So(LogSplitHour.String(), ShouldEqual, "HOUR")
So(string(byteData), ShouldEqual, `"HOUR"`)
})
Convey("logger split MarshalJSON", t, func() {
str, err := LogSplitHour.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"HOUR"`)
dataList := []LogSplit{LogSplitHour}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["HOUR"]`)
})
}
func TestLogSplit_IsValid(t *testing.T) {
Convey("logger split 非法验证", t, func() {
So(LogSplit("Invalid").IsValid(), ShouldBeFalse)
})
Convey("logger split 合法验证", t, func() {
So(LogSplit("HOUR").IsValid(), ShouldBeTrue)
})
}

View File

@ -96,6 +96,8 @@ const (
MimeTypeImagePng = "image/png"
// MimeTypeJson json数据格式
MimeTypeJson = "application/json"
// MimeTypeTextPlain text/plain
MimeTypeTextPlain = "text/plain"
// MimeTypeXWWWFormUrlencoded <form encType=””>中默认的encTypeform表单数据被编码为key/value格式发送到服务器表单默认的提交数据的格式
MimeTypeXWWWFormUrlencoded = "application/x-www-form-urlencoded"
// MimeTypeXml xml请求方式

View File

@ -9,11 +9,15 @@ package consts
type RedisCmd string
func (rc *RedisCmd) String() string {
return string(*rc)
func (rc RedisCmd) String() string {
return string(rc)
}
func (rc *RedisCmd) MarshalJSON() ([]byte, error) {
func (rc RedisCmd) MarshalJSON() ([]byte, error) {
return []byte(`"` + rc.String() + `"`), nil
}
func (rc RedisCmd) MarshalBinary() ([]byte, error) {
return []byte(rc.String()), nil
}

38
redis_test.go Normal file
View File

@ -0,0 +1,38 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 13:29
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
// RedisCmd_String 序列换 RedisCmd
func TestRedisCmd_String(t *testing.T) {
Convey("redis cmd字符串值", t, func() {
byteData, err := json.Marshal(RedisCommandSet)
So(err, ShouldBeNil)
So(RedisCommandSet.String(), ShouldEqual, "SET")
So(string(byteData), ShouldEqual, `"SET"`)
})
Convey("redis cmd MarshalJSON", t, func() {
str, err := RedisCommandSet.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"SET"`)
dataList := []RedisCmd{RedisCommandSet}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["SET"]`)
})
Convey("redis cmd MarshalBinary", t, func() {
str, err := RedisCommandSet.MarshalBinary()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `SET`)
})
}

View File

@ -19,36 +19,12 @@ func (rdl RequestDataLocation) String() string {
}
func (rdl RequestDataLocation) MarshalJSON() ([]byte, error) {
return []byte(rdl.String()), nil
return []byte(`"` + rdl.String() + `"`), nil
}
func (rdl RequestDataLocation) IsValid() bool {
for _, item := range RequestDataLocationList {
if item.Value == rdl {
return true
}
}
return false
}
// ResponseDataLocation 响应数据所在位置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:41 2024/11/25
type ResponseDataLocation string
func (rdl *ResponseDataLocation) String() string {
return string(*rdl)
}
func (rdl *ResponseDataLocation) MarshalJSON() ([]byte, error) {
return []byte(rdl.String()), nil
}
func (rdl *ResponseDataLocation) IsValid() bool {
for _, item := range ResponseDataLocationList {
if item.Value == *rdl {
if item.Value == rdl || item.Value.String() == rdl.String() {
return true
}
}
@ -62,9 +38,34 @@ const (
RequestDataLocationQuery RequestDataLocation = "QUERY" // query
RequestDataLocationUriPath RequestDataLocation = "URI_PATH" // uri路由一部分
RequestDataLocationStatic RequestDataLocation = "STATIC" // 静态配置的参数
RequestDataLocationAny RequestDataLocation = "ANY" // 任意位置,要求服务支持从各种位置自动读取
RequestDataLocationCustomConfig RequestDataLocation = "CUSTOM_CONFIG" // 针对接口的一些自定义配置规则
)
// ResponseDataLocation 响应数据所在位置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:41 2024/11/25
type ResponseDataLocation string
func (rdl ResponseDataLocation) String() string {
return string(rdl)
}
func (rdl ResponseDataLocation) MarshalJSON() ([]byte, error) {
return []byte(`"` + rdl.String() + `"`), nil
}
func (rdl ResponseDataLocation) IsValid() bool {
for _, item := range ResponseDataLocationList {
if item.Value == rdl || item.Value.String() == rdl.String() {
return true
}
}
return false
}
const (
ResponseDataLocationHeader ResponseDataLocation = "HEADER" // header
ResponseDataLocationCookie ResponseDataLocation = "COOKIE" // cookie
@ -90,6 +91,7 @@ var (
{Value: RequestDataLocationBody, Description: "请求body"},
{Value: RequestDataLocationQuery, Description: "请求query"},
{Value: RequestDataLocationUriPath, Description: "请求uri_path"},
{Value: RequestDataLocationAny, Description: "任意位置,要求服务本身支持"},
{Value: RequestDataLocationStatic, Description: "静态参数配置"},
{Value: RequestDataLocationCustomConfig, Description: "自定义接口处理规则"},
}

68
request_test.go Normal file
View File

@ -0,0 +1,68 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 14:37
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestRequestDataLocation_String(t *testing.T) {
Convey("request data location字符串值", t, func() {
byteData, err := json.Marshal(RequestDataLocationBody)
So(err, ShouldBeNil)
So(RequestDataLocationBody.String(), ShouldEqual, "BODY")
So(string(byteData), ShouldEqual, `"BODY"`)
})
Convey("request data location MarshalJSON", t, func() {
str, err := RequestDataLocationBody.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"BODY"`)
dataList := []RequestDataLocation{RequestDataLocationBody}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["BODY"]`)
})
}
func TestRequestDataLocation_IsValid(t *testing.T) {
Convey("request data location 非法验证", t, func() {
So(RequestDataLocation("Invalid").IsValid(), ShouldBeFalse)
})
Convey("request data location 合法验证", t, func() {
So(RequestDataLocation("BODY").IsValid(), ShouldBeTrue)
})
}
func TestResponseDataLocation_String(t *testing.T) {
Convey("response data location字符串值", t, func() {
byteData, err := json.Marshal(ResponseDataLocationBody)
So(err, ShouldBeNil)
So(RequestDataLocationBody.String(), ShouldEqual, "BODY")
So(string(byteData), ShouldEqual, `"BODY"`)
})
Convey("response data location MarshalJSON", t, func() {
str, err := ResponseDataLocationBody.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"BODY"`)
dataList := []ResponseDataLocation{ResponseDataLocationBody}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["BODY"]`)
})
}
func TestResponseDataLocation_IsValid(t *testing.T) {
Convey("response data location 非法验证", t, func() {
So(ResponseDataLocation("Invalid").IsValid(), ShouldBeFalse)
})
Convey("response data location 合法验证", t, func() {
So(ResponseDataLocation("BODY").IsValid(), ShouldBeTrue)
})
}

View File

@ -9,15 +9,15 @@ package consts
type HttpScheme string
func (hs *HttpScheme) String() string {
return string(*hs)
func (hs HttpScheme) String() string {
return string(hs)
}
func (hs *HttpScheme) MarshalJSON() ([]byte, error) {
return []byte(hs.String()), nil
func (hs HttpScheme) MarshalJSON() ([]byte, error) {
return []byte(`"` + hs.String() + `"`), nil
}
const (
var (
SchemeHTTP HttpScheme = "http"
SchemeHTTPS HttpScheme = "https"
SchemeWs HttpScheme = "ws"

32
scheme_test.go Normal file
View File

@ -0,0 +1,32 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 15:47
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestHttpScheme_String(t *testing.T) {
Convey("scheme 字符串值", t, func() {
byteData, err := json.Marshal(SchemeHTTPS)
So(err, ShouldBeNil)
So(SchemeHTTPS.String(), ShouldEqual, "https")
So(string(byteData), ShouldEqual, `"https"`)
})
Convey("scheme MarshalJSON", t, func() {
str, err := SchemeHTTPS.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"https"`)
dataList := []HttpScheme{SchemeHTTPS}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["https"]`)
})
}

View File

@ -24,7 +24,7 @@ const (
)
const (
SwaggerDocVersion2 = "2.0.0"
SwaggerDocVersion2 = "2.0"
SwaggerDocVersion3 = "3.0.0"
)

566
validator.go Normal file
View File

@ -0,0 +1,566 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-01-22 16:08
// @see: https://github.com/go-playground/validator/blob/master/README.md#strings
// @demo: https://www.cnblogs.com/zj420255586/p/13542395.html
package consts
type ValidatorRule string // 验证规则
func (vr ValidatorRule) String() string {
return string(vr)
}
func (vr ValidatorRule) MarshalJSON() ([]byte, error) {
return []byte(`"` + vr.String() + `"`), nil
}
// IsValid 验证规则是否有效
func (vr ValidatorRule) IsValid() bool {
_, exist := ValidatorRuleSupportDataTypeTable[vr]
if !exist {
return false
}
rule := ValidatorRuleSupportDataTypeTable[vr].ValidatorRule
if vr.String() != rule.String() {
return false
}
return exist
}
// Config 验证规则的配置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:10 2025/1/22
func (vr ValidatorRule) Config() ValidatorRuleConfig {
return ValidatorRuleSupportDataTypeTable[vr]
}
// IsSupportDataType 是否支持指定的数据类型
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:11 2025/1/22
func (vr ValidatorRule) IsSupportDataType(dataType DataType) bool {
dataTypeList := vr.Config().SupportDataTypeList
if len(dataTypeList) == 0 {
// 未配置则认为支持
return true
}
for _, dataTypeItem := range dataTypeList {
if dataType.String() == dataTypeItem.String() {
return true
}
}
return false
}
type ValidatorRuleConfig struct {
ValidatorRule ValidatorRule `json:"validator_rule"` // 验证规则
Description string `json:"description"` // 规则描述
SupportDataTypeList []DataType `json:"support_data_type_list"` // 支持的数据类型列表
MinParamCnt int `json:"min_param_cnt"` // 最小参数数量(闭区间)
MaxParamCnt int `json:"max_param_cnt"` // 最大参数数量(闭区间)
ParamCntMustEven bool `json:"param_cnt_must_even"` // 参数数量必须是偶数
WithoutParam bool `json:"without_param"` // 没有参数, 此值为 true, 忽略 MinParamCnt / MaxParamCnt / ParamCntMustEven
}
// ValidatorRuleSupportDataTypeTable 验证规则支持的数据类型表
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:13 2025/1/22
var ValidatorRuleSupportDataTypeTable = map[ValidatorRule]ValidatorRuleConfig{
ValidatorRuleEqcsfield: {
ValidatorRule: ValidatorRuleEqcsfield,
Description: "跨结构体字段相等",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleEqfield: {
ValidatorRule: ValidatorRuleEqfield,
Description: "同结构体字段相等",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleFieldcontains: {
ValidatorRule: ValidatorRuleFieldcontains,
Description: "检查指定的字段值是否存在于字段中",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidatorRuleFieldexcludes: {
ValidatorRule: ValidatorRuleFieldexcludes,
Description: "检查指定的字段值是否不存在于字段中",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidatorRuleGtcsfield: {
ValidatorRule: ValidatorRuleGtcsfield,
Description: "大于(跨结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleGtecsfield: {
ValidatorRule: ValidatorRuleGtecsfield,
Description: "大于(同结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleGtfield: {
ValidatorRule: ValidatorRuleGtfield,
Description: "大于(同结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleGtefield: {
ValidatorRule: ValidatorRuleGtefield,
Description: "大于(同结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleLtcsfield: {
ValidatorRule: ValidatorRuleLtcsfield,
Description: "小于(跨结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleLtecsfield: {
ValidatorRule: ValidatorRuleLtecsfield,
Description: "小于等于(跨结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleLtfield: {
ValidatorRule: ValidatorRuleLtfield,
Description: "小于(同结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleLtefield: {
ValidatorRule: ValidatorRuleLtefield,
Description: "小于等于(同结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleNecsfield: {
ValidatorRule: ValidatorRuleNecsfield,
Description: "不等于(跨结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidatorRuleNefield: {
ValidatorRule: ValidatorRuleNefield,
Description: "不等于(同结构体)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidateRuleEq: {
ValidatorRule: ValidateRuleEq,
Description: "等于(严格校验)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidateRuleEqIgnoreCase: {
ValidatorRule: ValidateRuleEqIgnoreCase,
Description: "等于(忽略大小写)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 1,
ParamCntMustEven: false,
},
ValidateRuleGt: {
ValidatorRule: ValidateRuleGt,
Description: "大于",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidateRuleGte: {
ValidatorRule: ValidateRuleGte,
Description: "大于等于",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidateRuleLt: {
ValidatorRule: ValidateRuleLt,
Description: "小于",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidateRuleLte: {
ValidatorRule: ValidateRuleLte,
Description: "小于等于",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidateRuleNe: {
ValidatorRule: ValidateRuleNe,
Description: "不等于(严格判断)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidateRuleNeIgnoreCase: {
ValidatorRule: ValidateRuleNeIgnoreCase,
Description: "不等于(忽略大小写)",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
MinParamCnt: 1,
MaxParamCnt: 0,
ParamCntMustEven: false,
},
ValidatorRuleCommonDir: {
ValidatorRule: ValidatorRuleCommonDir,
Description: "文件夹存在",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
WithoutParam: true,
},
ValidatorRuleCommonDirPath: {
ValidatorRule: ValidatorRuleCommonDirPath,
Description: "文件夹路径存在",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
WithoutParam: true,
},
ValidatorRuleCommonFile: {
ValidatorRule: ValidatorRuleCommonFile,
Description: "文件存在",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
WithoutParam: true,
},
ValidatorRuleCommonFilepath: {
ValidatorRule: ValidatorRuleCommonFilepath,
Description: "文件路径存在",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
WithoutParam: true,
},
ValidatorRuleCommonImage: {
ValidatorRule: ValidatorRuleCommonImage,
Description: "是否图像资源",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal),
WithoutParam: true,
},
ValidatorRuleCommonIsDefault: {
ValidatorRule: ValidatorRuleCommonIsDefault,
Description: "是否对应类型默认值",
SupportDataTypeList: nil, // 所有类型均支持
WithoutParam: true,
},
ValidatorRuleCommonOmitempty: {
ValidatorRule: ValidatorRuleCommonOmitempty,
Description: "为空时不进行其他校验",
SupportDataTypeList: nil, // 所有类型均支持
WithoutParam: true,
},
ValidatorRuleCommonLen: {
ValidatorRule: ValidatorRuleCommonLen,
Description: "数据长度",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString, DataTypeSliceMarshal, DataTypeSliceSplit, DataTypeMapMarshal, DataTypeSlice, DataTypeMap), // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 1,
},
ValidatorRuleCommonMax: {
ValidatorRule: ValidatorRuleCommonMax,
Description: "最大值",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
},
ValidatorRuleCommonMin: {
ValidatorRule: ValidatorRuleCommonMin,
Description: "最小值",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
MinParamCnt: 1,
MaxParamCnt: 1,
},
ValidatorRuleCommonOneOf: {
ValidatorRule: ValidatorRuleCommonOneOf,
Description: "枚举值",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber, DataTypeBaseString, DataTypeBaseBool),
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonRequired: {
ValidatorRule: ValidatorRuleCommonRequired,
Description: "必传校验",
SupportDataTypeList: nil, // 所有类型均支持
WithoutParam: true,
},
ValidatorRuleCommonRequiredIf: {
ValidatorRule: ValidatorRuleCommonRequiredIf,
Description: "当指定字段等于给定值时, 必传校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 2,
MaxParamCnt: 0,
ParamCntMustEven: true,
},
ValidatorRuleCommonRequiredUnless: {
ValidatorRule: ValidatorRuleCommonRequiredUnless,
Description: "当指定字段不等于给定值时, 必传校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 2,
MaxParamCnt: 0,
ParamCntMustEven: true,
},
ValidatorRuleCommonRequiredWith: {
ValidatorRule: ValidatorRuleCommonRequiredWith,
Description: "当任意一个指定字段不为零值时, 必传校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonRequiredWithAll: {
ValidatorRule: ValidatorRuleCommonRequiredWithAll,
Description: "当全部指定字段不为零值时, 必传校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonRequiredWithout: {
ValidatorRule: ValidatorRuleCommonRequiredWithout,
Description: "当任意一个字段不存在时, 必传校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonRequiredWithoutAll: {
ValidatorRule: ValidatorRuleCommonRequiredWithoutAll,
Description: "当全部字段不存在时, 必传校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonExcludedIf: {
ValidatorRule: ValidatorRuleCommonExcludedIf,
Description: "当指定字段等于给定值时,排除校验",
SupportDataTypeList: nil, // 所有类型均支持
},
ValidatorRuleCommonExcludedUnless: {
ValidatorRule: ValidatorRuleCommonExcludedUnless,
Description: "当指定字段等于给定值时,排除校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 2,
MaxParamCnt: 0,
ParamCntMustEven: true,
},
ValidatorRuleCommonExcludedWith: {
ValidatorRule: ValidatorRuleCommonExcludedWith,
Description: "当全部指定字段不为零值时,排除校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 2,
MaxParamCnt: 0,
ParamCntMustEven: true,
},
ValidatorRuleCommonExcludedWithAll: {
ValidatorRule: ValidatorRuleCommonExcludedWithAll,
Description: "当全部指定字段不为零值时,排除校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonExcludedWithout: {
ValidatorRule: ValidatorRuleCommonExcludedWithout,
Description: "当任意一个指定字段不存在时,排除校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonExcludedWithoutAll: {
ValidatorRule: ValidatorRuleCommonExcludedWithoutAll,
Description: "当全部指定字段不存在时,排除校验",
SupportDataTypeList: nil, // 所有类型均支持
MinParamCnt: 1,
MaxParamCnt: 0,
},
ValidatorRuleCommonUnique: {
ValidatorRule: ValidatorRuleCommonUnique,
Description: "是否唯一, 用于切片验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeSlice), // 所有类型均支持
WithoutParam: true,
},
ValidatorRuleFormatterCron: {
ValidatorRule: ValidatorRuleFormatterCron,
Description: "cron表达式验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterEmail: {
ValidatorRule: ValidatorRuleFormatterEmail,
Description: "邮箱地址验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterJson: {
ValidatorRule: ValidatorRuleFormatterJson,
Description: "json格式验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterJwt: {
ValidatorRule: ValidatorRuleFormatterJson,
Description: "JWT(JSON Web Token)验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterLatitude: {
ValidatorRule: ValidatorRuleFormatterLatitude,
Description: "纬度验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
WithoutParam: true,
},
ValidatorRuleFormatterLongitude: {
ValidatorRule: ValidatorRuleFormatterLongitude,
Description: "经度验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseNumber),
WithoutParam: true,
},
ValidatorRuleFormatterTimezone: {
ValidatorRule: ValidatorRuleFormatterLongitude,
Description: "时区验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterUrl: {
ValidatorRule: ValidatorRuleFormatterUrl,
Description: "url验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterUri: {
ValidatorRule: ValidatorRuleFormatterUrl,
Description: "uri验证",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterLowercase: {
ValidatorRule: ValidatorRuleFormatterLowercase,
Description: "仅包含小写字符",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
ValidatorRuleFormatterUppercase: {
ValidatorRule: ValidatorRuleFormatterUppercase,
Description: "仅包含大写字符",
SupportDataTypeList: getMergeDataTypeList(DataTypeBaseString),
WithoutParam: true,
},
}
var (
// ValidatorRuleEqcsfield .....Fields ..............
ValidatorRuleEqcsfield ValidatorRule = "eqcsfield" // 跨结构体字段相等 eqcsfield={{struct.field}}
ValidatorRuleEqfield ValidatorRule = "eqfield" // 同结构体字段相等 eqfield={{struct.field}}
ValidatorRuleFieldcontains ValidatorRule = "fieldcontains" // 检查指定的字段值是否存在于字段中 fieldcontains={{struct.field}}
ValidatorRuleFieldexcludes ValidatorRule = "fieldexcludes" // 检查指定的字段值是否存在于字段中 fieldexcludes={{struct.field}}
ValidatorRuleGtcsfield ValidatorRule = "gtcsfield" // 大于(跨结构体) gtcsfield={{struct.field}}
ValidatorRuleGtecsfield ValidatorRule = "gtecsfield" // 大于等于(跨结构体) gtecsfield={{struct.field}}
ValidatorRuleGtfield ValidatorRule = "gtfield" // 大于(同结构体) gtfield={{struct.field}}
ValidatorRuleGtefield ValidatorRule = "gtefield" // 大于等于(同结构体) gtefield={{struct.field}}
ValidatorRuleLtcsfield ValidatorRule = "ltcsfield" // 小于(跨结构体) ltcsfield={{struct.field}}
ValidatorRuleLtecsfield ValidatorRule = "ltecsfield" // 小于等于(跨结构体) ltecsfield={{struct.field}}
ValidatorRuleLtfield ValidatorRule = "ltfield" // 小于(同结构体) ltfield={{struct.field}}
ValidatorRuleLtefield ValidatorRule = "ltefield" // 小于等于(同结构体) ltefield={{struct.field}}
ValidatorRuleNecsfield ValidatorRule = "necsfield" // 不等于(跨结构体) necsfield={{struct.field}}
ValidatorRuleNefield ValidatorRule = "nefield" // 不等于(同结构体) nefield={{struct.field}}
// ValidateRuleEq Comparisons ....................
ValidateRuleEq ValidatorRule = "eq" // 相等(严格判断) eq={{any_value}}
ValidateRuleEqIgnoreCase ValidatorRule = "eq_ignore_case" // 相等(忽略大小写) eq_ignore_case={{any_value}}
ValidateRuleGt ValidatorRule = "gt" // 大于 gt={{number_value}}
ValidateRuleGte ValidatorRule = "gte" // 大于等于 gte={{number_value}}
ValidateRuleLt ValidatorRule = "lt" // 小于 lt={{number_value}}
ValidateRuleLte ValidatorRule = "lte" // 小于等于 lte={{number_value}}
ValidateRuleNe ValidatorRule = "ne" // 不相等(严格判断) ne={{any_value}}
ValidateRuleNeIgnoreCase ValidatorRule = "ne_ignore_case" // 不相等(忽略大小写) ne_ignore_case={{any_value}}
// ValidatorRuleCommonDir ............others
ValidatorRuleCommonDir ValidatorRule = "dir" // 文件夹存在
ValidatorRuleCommonDirPath ValidatorRule = "dirpath" // 文件夹路径
ValidatorRuleCommonFile ValidatorRule = "file" // 文件存在
ValidatorRuleCommonFilepath ValidatorRule = "filepath" // 文件路径
ValidatorRuleCommonImage ValidatorRule = "image" // 图像
ValidatorRuleCommonIsDefault ValidatorRule = "isdefault" // 是否默认值
ValidatorRuleCommonOmitempty ValidatorRule = "omitempty" // 为空忽略,比如,某些字段可以不传或者传空, 但是一旦传了则必须是制定枚举值, omitempty,oneof=a b
ValidatorRuleCommonLen ValidatorRule = "len" // 长度 len={{uint_value}}
ValidatorRuleCommonMax ValidatorRule = "max" // 最大值 max={{int_value}}
ValidatorRuleCommonMin ValidatorRule = "min" // 最小值 min={{int_value}}
ValidatorRuleCommonOneOf ValidatorRule = "oneof" // 枚举值, 多个空格分隔 oneof={{enum1}} {{enum2}} {{enum....}}
ValidatorRuleCommonRequired ValidatorRule = "required" // 必传
ValidatorRuleCommonRequiredIf ValidatorRule = "required_if" // 当指定字段等于给定值时,校验必传 required_if={{check_field}} {{check_field_value}} {{check_field...}} {{check_field_value...}}
ValidatorRuleCommonRequiredUnless ValidatorRule = "required_unless" // 当指定字段不等于给定值时,校验必传 required_if={{check_field}} {{check_field_value}} {{check_field...}} {{check_field_value...}}
ValidatorRuleCommonRequiredWith ValidatorRule = "required_with" // 当任意一个指定字段不为零值时, 校验必传 required_with={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonRequiredWithAll ValidatorRule = "required_with_all" // 当全部指定字段不为零值时, 校验必传 required_with={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonRequiredWithout ValidatorRule = "required_without" // 任意一个字段为空时,必传校验 required_without={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonRequiredWithoutAll ValidatorRule = "required_without_all" // 全部字段为空时,必传校验 required_without_all={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonExcludedIf ValidatorRule = "excluded_if" // 当指定字段等于给定值时,排除校验 excluded_if={{check_field}} {{check_field_value}} {{check_field...}} {{check_field_value...}}
ValidatorRuleCommonExcludedUnless ValidatorRule = "excluded_unless" // 当指定字段不等于给定值时,排除校验 excluded_if={{check_field}} {{check_field_value}} {{check_field...}} {{check_field_value...}}
ValidatorRuleCommonExcludedWith ValidatorRule = "excluded_with" // 当任意一个指定字段不为零值时,排除校验 excluded_with={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonExcludedWithAll ValidatorRule = "excluded_with_all" // 当全部指定字段不为零值时,排除校验 excluded_with_all={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonExcludedWithout ValidatorRule = "excluded_without" // 当任意一个指定字段不存在时,排除校验 excluded_without={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonExcludedWithoutAll ValidatorRule = "excluded_without_all" // 当q廍指定字段不存在时,排除校验 excluded_without-all={{Field1}} {{Field2}} {{Field...}}
ValidatorRuleCommonUnique ValidatorRule = "unique" // 数据唯一校验
// ValidatorRuleFormatterCron ............. formatter
ValidatorRuleFormatterCron ValidatorRule = "cron" // cron表达式
ValidatorRuleFormatterEmail ValidatorRule = "email" // 邮件地址
ValidatorRuleFormatterJson ValidatorRule = "json" // json格式
ValidatorRuleFormatterJwt ValidatorRule = "jwt" // JSON Web Token (JWT)
ValidatorRuleFormatterLatitude ValidatorRule = "latitude" // 纬度
ValidatorRuleFormatterLongitude ValidatorRule = "longitude" // 经度
ValidatorRuleFormatterTimezone ValidatorRule = "timezone" // 时区
ValidatorRuleFormatterUrl ValidatorRule = "url" // url
ValidatorRuleFormatterUri ValidatorRule = "uri" // uri
ValidatorRuleFormatterLowercase ValidatorRule = "lowercase" // 仅包含小写字符
ValidatorRuleFormatterUppercase ValidatorRule = "uppercase" // 仅包含大写字符
)
// RegisterCustomValidatorRule 注册自定义的验证方法, 允许通过此函数, 覆盖内部默认的配置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:35 2025/1/24
func RegisterCustomValidatorRule(rule ValidatorRule, validatorRuleConfig ValidatorRuleConfig) {
ValidatorRuleSupportDataTypeTable[rule] = validatorRuleConfig
}

64
validator_test.go Normal file
View File

@ -0,0 +1,64 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-20 17:37
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestValidatorRule_String(t *testing.T) {
Convey("validate rule 字符串值", t, func() {
byteData, err := json.Marshal(ValidateRuleGt)
So(err, ShouldBeNil)
So(ValidateRuleGt.String(), ShouldEqual, "gt")
So(string(byteData), ShouldEqual, `"gt"`)
})
Convey("validate rule MarshalJSON", t, func() {
str, err := ValidateRuleGt.MarshalJSON()
So(err, ShouldBeNil)
So(string(str), ShouldEqual, `"gt"`)
dataList := []ValidatorRule{ValidateRuleGt}
jsonData, err := json.Marshal(dataList)
So(err, ShouldBeNil)
So(string(jsonData), ShouldEqual, `["gt"]`)
})
}
func TestValidatorRule_IsValid(t *testing.T) {
Convey("validator rule 不存在", t, func() {
So(ValidatorRule("Invalid").IsValid(), ShouldBeFalse)
})
Convey("validator rule 配置值错误", t, func() {
ValidatorRuleSupportDataTypeTable[ValidatorRule("Invalid")] = ValidatorRuleConfig{}
So(ValidatorRule("Invalid").IsValid(), ShouldBeFalse)
So(ValidatorRule("gt").IsValid(), ShouldBeTrue)
})
Convey("validator rule 配置值", t, func() {
So(ValidatorRuleGtcsfield.Config().MinParamCnt, ShouldEqual, 1)
})
}
func TestValidatorRule_IsSupportDataType(t *testing.T) {
Convey("validator rule 是否支持指定数据类型", t, func() {
So(ValidatorRuleGtcsfield.IsSupportDataType(DataTypeUint), ShouldBeTrue)
So(ValidatorRuleGtcsfield.IsSupportDataType(DataTypeString), ShouldBeFalse)
})
Convey("validator rule 未指定类型默认支持", t, func() {
So(ValidatorRuleCommonOmitempty.IsSupportDataType(DataTypeString), ShouldBeTrue)
})
}
func TestRegisterCustomValidatorRule(t *testing.T) {
Convey("注册自定义验证规则", t, func() {
RegisterCustomValidatorRule(ValidatorRule("Invalid"), ValidatorRuleConfig{})
_, exist := ValidatorRuleSupportDataTypeTable[ValidatorRule("Invalid")]
So(exist, ShouldBeTrue)
})
}