Compare commits

...

77 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
5ecf3edb4a Merge pull request '修复自定义Marshal序列化的BUG' (#1) from feature/upgrade_marshal into master
Reviewed-on: #1
2025-01-22 15:57:09 +08:00
10759d9c5e 修复自定义Marshal序列化的BUG 2025-01-22 15:55:39 +08:00
c00354fe46 响应数据增加BODY_ROOT 2024-12-25 11:07:57 +08:00
b1b286c7a7 升级日志切割类型定义 2024-11-25 18:08:43 +08:00
cacc6b3caf 更新枚举类型定义 2024-11-25 16:15:57 +08:00
f919222003 优化枚举值定义 2024-11-25 14:51:14 +08:00
325efde765 请求类型枚举值定义 2024-11-25 14:43:40 +08:00
1f5050978f 数据类型使用枚举值类型定义 2024-11-25 14:13:50 +08:00
0f97a870bb fix xml 2024-11-04 16:21:08 +08:00
ab1d691f30 增加contentType xml定义 2024-11-04 16:18:23 +08:00
10cff91730 update file type 2024-10-23 17:06:05 +08:00
b6f4a65127 参数数据位置支持 : STATIC / CUSTOM_CONFIG 2024-10-15 11:50:56 +08:00
d8400fb206 增加redis命令枚举值 2024-10-09 18:17:09 +08:00
1d415ef93c 增加redis命令枚举值 2024-10-09 18:13:40 +08:00
0b1c661317 增加redis命令枚举值 2024-10-08 16:41:26 +08:00
c865046cd9 update 2024-09-24 14:50:29 +08:00
d4df71cf37 增加 where operate 枚举值 2024-08-23 12:11:45 +08:00
8bf75bab08 增加sqlType枚举值 2024-08-21 16:27:58 +08:00
491f455a23 update const 2024-08-17 17:15:13 +08:00
e424db29c5 增加output日志类型 2024-07-26 10:49:39 +08:00
6c9a149fb3 fix const 2024-07-25 16:23:45 +08:00
d078492636 增加日志类型枚举值 2024-07-24 22:00:52 +08:00
ee05107535 增加Gin相关枚举值 2024-07-23 16:50:16 +08:00
ca68a3ff8b 增加定义swagger 2024-07-22 16:00:05 +08:00
afb5d1d933 增加swagger parameter style定义 2024-07-19 15:56:38 +08:00
d39136c71c 增加swagger parameter style定义 2024-07-19 15:42:12 +08:00
92231690b0 增加 swagger parameter in 属性枚举值定义 2024-07-19 15:28:29 +08:00
8556a14a13 更新swagger枚举值定义 2024-07-19 14:43:07 +08:00
e1e2a2e421 数据类型支持基础的指针类型 2024-07-09 21:41:22 +08:00
c3417b35fe 增加事件驱动定义 2024-06-25 15:55:35 +08:00
2598eb986e 增加日志一些变量的枚举值 2024-06-24 16:36:52 +08:00
92f8bcd8ed fix log split 2024-06-24 16:08:03 +08:00
16438ccb00 增加日志常量定义 2024-06-24 15:49:49 +08:00
0d14e24110 增加最大端口号和最小端口号定义 2024-06-24 12:14:16 +08:00
f7667bcc76 增加数据位置定义 2024-06-23 14:01:47 +08:00
b83cc0dd45 增加数据类型描述 2024-06-23 13:51:43 +08:00
2fea122027 增加数据类型的定义 2024-06-23 11:12:47 +08:00
666060e4de 增加缓存驱动的定义 2024-06-21 14:51:39 +08:00
39e82fd033 rename sqlite => sqlite3 2024-06-17 15:36:16 +08:00
bf96f1ebd5 增加数据库驱动定义 2024-06-17 11:18:27 +08:00
31c64d4d4c 增加数据类型枚举 2024-06-12 16:17:22 +08:00
4d97bd80dc 增加respone枚举值 2024-06-08 20:45:42 +08:00
4311f44fab 增加slice any 类型枚举 2024-06-08 19:57:00 +08:00
feddc6a70f Merge branch 'master' of git.zhangdeman.cn:zhangdeman/consts 2024-06-08 18:40:35 +08:00
a6081f7a98 fix 2024-06-08 18:40:25 +08:00
27 changed files with 2210 additions and 89 deletions

14
cache.go Normal file
View File

@ -0,0 +1,14 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-06-21 14:49
package consts
const (
CacheDriverRedis = "redis" // redis缓存驱动
CacheDriverGocache = "gocache" // gocache缓存驱动
CacheDriverMemcached = "memcached" // memcache缓存驱动
)

View File

@ -7,34 +7,107 @@
// Date : 2024-04-08 16:33
package consts
const (
DataTypeInt = "int" // int类型 -> int64
DataTypeUint = "uint" // uint类型 -> uint64
DataTypeFloat = "float" // float类型 -> float64
DataTypeBool = "bool" // bool类型
DataTypeString = "string" // 字符串类型
DataTypeSliceInt = "[]int" // int数组 -> []int64
DataTypeSliceIntWithChar = "[]int_split" // int数组 -> []int64, 按照指定字符切割
DataTypeSliceUint = "[]uint" // uint数组 -> []uint64
DataTypeSliceUintWithChar = "[]uint_split" // uint数组 -> []uint64 指定字符切割
DataTypeSliceFloat = "[]float" // float数组 -> []float64
DataTypeSliceFloatWithChar = "[]float_split" // float数组 -> []float64, 指定字符切割
DataTypeSliceBool = "[]bool" // bool数组 -> []bool
DataTypeSliceBoolWithChar = "[]bool_split" // bool数组 -> []bool, 指定字符切割
DataTypeSliceString = "[]string" // 字符串数组 -> []string
DataTypeSliceStringWithChar = "[]string_split" // 字符串数组 -> []string, 指定字符切割
DataTypeSliceSlice = "[][]any" // 字符串数组 -> [][]any
DataTypeSliceMapAnyAny = "[]map[any]any" // 字符串数组 -> map[any]any, slice对象
DataTypeSliceMapStringAny = "[]map[string]any" // 字符串数组 -> map[string]any, slice对象
DataTypeMapStrInt = "map[string]int" // map -> map[string]int64
DataTypeMapStrUint = "map[string]uint" // map -> map[string]uint64
DataTypeMapStrFloat = "map[string]float" // map -> map[string]float64
DataTypeMapStrBool = "map[string]bool" // map -> map[string]bool
DataTypeMapStrAny = "map[string]any" // map -> map[string]interface{}
DataTypeMapStrStr = "map[string]string" // map -> map[string]string
DataTypeMapAnyAny = "map[any]any" // map -> map[interface{}]interface{}
DataTypeMapStrSlice = "map[string][]any" // map -> map[string][]interface{}
DataTypeAny = "any" // 任意类型 -> interface{}
// DataType 数据类型枚举值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:10 2024/11/25
type DataType string
func (df DataType) String() string {
return string(df)
}
func (df DataType) MarshalJSON() ([]byte, error) {
return []byte(`"` + df.String() + `"`), nil
}
// IsValid 判断枚举值是否有效
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:45 2024/11/25
func (df DataType) IsValid() bool {
for _, item := range DataTypeList {
if item.Value == df || item.Value.String() == df.String() {
return true
}
}
return false
}
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
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
DataTypeSliceAnyWithMarshal DataType = "[]any_marshal" // any数组 -> []any, json序列化之后的结构
DataTypeSliceInt DataType = "[]int" // int数组 -> []int64
DataTypeSliceIntWithChar DataType = "[]int_split" // int数组 -> []int64, 按照指定字符切割
DataTypeSliceIntWithMarshal DataType = "[]int_marshal" // int数组 -> []int64, json序列化之后的结果
DataTypeSliceUint DataType = "[]uint" // uint数组 -> []uint64
DataTypeSliceUintWithChar DataType = "[]uint_split" // uint数组 -> []uint64 指定字符切割
DataTypeSliceUintWithMarshal DataType = "[]uint_marshal" // uint数组 -> []uint64 json序列化之后的结果
DataTypeSliceFloat DataType = "[]float" // float数组 -> []float64
DataTypeSliceFloatWithChar DataType = "[]float_split" // float数组 -> []float64, 指定字符切割
DataTypeSliceFloatWithMarshal DataType = "[]float_marshal" // float数组 -> []float64, json序列化之后的结果
DataTypeSliceBool DataType = "[]bool" // bool数组 -> []bool
DataTypeSliceBoolWithChar DataType = "[]bool_split" // bool数组 -> []bool, 指定字符切割
DataTypeSliceBoolWithMarshal DataType = "[]bool_marshal" // bool数组 -> []bool, json序列化之后的结果
DataTypeSliceString DataType = "[]string" // 字符串数组 -> []string
DataTypeSliceStringWithChar DataType = "[]string_split" // 字符串数组 -> []string, 指定字符切割
DataTypeSliceStringWithMarshal DataType = "[]string_marshal" // 字符串数组 -> []string, json序列化之后的结果
DataTypeSliceSlice DataType = "[][]any" // 字符串数组 -> [][]any
DataTypeSliceSliceWithMarshal DataType = "[][]any_marshal" // 字符串数组 -> [][]any,json序列化之后的结果
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 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
DataTypeMapStrUintWithMarshal DataType = "map[string]uint_marshal" // map -> map[string]uint64, json序列化之后的结果
DataTypeMapStrFloat DataType = "map[string]float" // map -> map[string]float64
DataTypeMapStrFloatWithMarshal DataType = "map[string]float_marshal" // map -> map[string]float64, json序列化之后的结果
DataTypeMapStrBool DataType = "map[string]bool" // map -> map[string]bool
DataTypeMapStrBoolWithMarshal DataType = "map[string]bool_marshal" // map -> map[string]bool,json序列换之后的结果
DataTypeMapStrAny DataType = "map[string]any" // map -> map[string]any
DataTypeMapStrAnyWithMarshal DataType = "map[string]any_marshal" // map -> map[string]any, json序列化之后的结果
DataTypeMapStrStr DataType = "map[string]string" // map -> map[string]string
DataTypeMapStrStrWithMarshal DataType = "map[string]string_marshal" // map -> map[string]string, json序列化之后的结果
DataTypeMapAnyAny DataType = "map[any]any" // map -> map[any]any
DataTypeMapAnyAnyWithMarshal DataType = "map[any]any_marshal" // map -> map[any]any, json序列化之后的结果
DataTypeMapStrSlice DataType = "map[string][]any" // map -> map[string][]any
DataTypeMapStrSliceWithMarshal DataType = "map[string][]any_marshal" // map -> map[string][]any, json 序列化之后的结果
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指针
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, 字符串指针
)
const (
@ -50,3 +123,310 @@ const (
DataSliceModelMarshal = "MARSHAL"
DataSliceModelWithSplitChar = "WITH_SPLIT_CHAR"
)
const (
DataMapModelReal = "REAL"
DataMapModelMarshal = "MARSHAL"
)
// DataTypeDesc 数据类型描述
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 13:22 2024/6/23
type DataTypeDesc struct {
Value DataType `json:"value"` // 具体数据类型
Description string `json:"description"` // 数据类型描述
}
var (
DataTypeList = []DataTypeDesc{
// 基础数据类型
getDataTypeDesc(DataTypeAny, "任意数据类型"),
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, "字符串类型"),
// map数据类型
getDataTypeDesc(DataTypeMapStrAny, "map[string]any"),
getDataTypeDesc(DataTypeMapStrAnyWithMarshal, "map[string]any json序列化之后的结果"),
getDataTypeDesc(DataTypeMapStrInt, "map[string]int64"),
getDataTypeDesc(DataTypeMapStrIntWithMarshal, "map[string]int64 json序列化之后的结果"),
getDataTypeDesc(DataTypeMapStrUint, "map[string]uint64"),
getDataTypeDesc(DataTypeMapStrUintWithMarshal, "map[string]uint64 json序列化之后的结果"),
getDataTypeDesc(DataTypeMapStrFloat, "map[string]float64"),
getDataTypeDesc(DataTypeMapStrFloatWithMarshal, "map[string]float64 json序列化之后的结果"),
getDataTypeDesc(DataTypeMapStrBool, "map[string]bool"),
getDataTypeDesc(DataTypeMapStrBoolWithMarshal, "map[string]bool json序列化之后的结果"),
getDataTypeDesc(DataTypeMapStrStr, "map[string]string"),
getDataTypeDesc(DataTypeMapStrStrWithMarshal, "map[string]string json序列化之后的结果"),
getDataTypeDesc(DataTypeMapAnyAny, "map[any]any"),
getDataTypeDesc(DataTypeMapAnyAnyWithMarshal, "map[any]any json序列化之后的结果"),
getDataTypeDesc(DataTypeMapStrSlice, "map[string][]any"),
getDataTypeDesc(DataTypeMapStrSliceWithMarshal, "map[string][]any json序列化之后的结果"),
// slice数据类型
getDataTypeDesc(DataTypeSliceAny, "[]any"),
getDataTypeDesc(DataTypeSliceString, "[]string"),
getDataTypeDesc(DataTypeSliceStringWithChar, "[]string 按照指定字符切割"),
getDataTypeDesc(DataTypeSliceStringWithMarshal, "[]string json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceAnyWithMarshal, "[]any json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceInt, "[]int"),
getDataTypeDesc(DataTypeSliceIntWithChar, "[]int 按照指定字符切割"),
getDataTypeDesc(DataTypeSliceIntWithMarshal, "[]int json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceUint, "[]uint"),
getDataTypeDesc(DataTypeSliceUintWithChar, "[]uint 按照指定字符切割"),
getDataTypeDesc(DataTypeSliceUintWithMarshal, "[]uint json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceFloat, "[]float"),
getDataTypeDesc(DataTypeSliceFloatWithChar, "[]float 按照指定字符切割"),
getDataTypeDesc(DataTypeSliceFloatWithMarshal, "[]float json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceBool, "[]bool"),
getDataTypeDesc(DataTypeSliceBoolWithChar, "[]bool 按照指定字符切割"),
getDataTypeDesc(DataTypeSliceBoolWithMarshal, "[]bool json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceSlice, "[][]any"),
getDataTypeDesc(DataTypeSliceSliceWithMarshal, "[][]any json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceMapStringAny, "[][]map[string]any"),
getDataTypeDesc(DataTypeSliceMapStringAnyWithMarshal, "[][]map[string]any json序列化之后的结果"),
getDataTypeDesc(DataTypeSliceMapAnyAny, "[]map[any]any"),
getDataTypeDesc(DataTypeSliceMapAnyAnyWithMarshal, "[]map[any]any json序列化之后的结果"),
// 基础类型的指针类型
getDataTypeDesc(DataTypeStringPtr, "*string, 字符串指针"),
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, 字符串指针"),
}
)
// getDataTypeDesc ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 13:24 2024/6/23
func getDataTypeDesc(value DataType, description string) DataTypeDesc {
return DataTypeDesc{
Value: value,
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)
})
}

37
database.go Normal file
View File

@ -0,0 +1,37 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-06-17 11:16
package consts
const (
DatabaseDriverMysql = "mysql" // mysql 数据库驱动
DatabaseDriverSqlite3 = "sqlite3" // sqlLite3 数据库驱动
)
const (
SqlTypeList = "list"
SqlTypeDetail = "detail"
SqlTypeCount = "count"
SqlTypeInsert = "insert"
SqlTypeUpdate = "update"
SqlTypeDelete = "delete"
)
// Equal , NotEqual , In , NotIn , Like, NotLike
const (
WhereOperateEqual = "equal" // =
WhereOperateNotEqual = "not_equal" // !=
WhereOperateIn = "in" // in
WhereOperateNotIn = "not_in" // not in
WhereOperateLike = "like" // like
WhereOperateNotLike = "not_like" // not like
)
const (
OrderRuleAsc = "asc" // 升序
OrderRuleDesc = "desc" // 降序
)

20
event.go Normal file
View File

@ -0,0 +1,20 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-06-25 15:48
package consts
const (
EventDriverNull = "null" // 禁用事件
EventDriverEtcd = "etcd" // etcd驱动
EventDriverKafka = "kafka" // kafka驱动
EventDriverRocketmq = "rocketmq" // rocketmq 驱动
EventDriverRedis = "redis" // redis驱动
EventDriverMysql = "mysql" // mysql驱动
EventDriverSqlite3 = "sqlite3" // sqlite3驱动(单机)
EventDriverLocal = "local-file" // 本地磁盘文件驱动(单机)
EventDriverMemory = "memory" // 内存驱动(单机)
)

View File

@ -7,21 +7,70 @@
// Date : 2023-08-11 10:59
package consts
type FileType string
func (ft FileType) String() string {
return string(ft)
}
func (ft FileType) MarshalJSON() ([]byte, error) {
return []byte(`"` + ft.String() + `"`), nil
}
func (ft FileType) IsValid() bool {
for _, fileType := range SupportFileTypeList {
if fileType.Value == ft || fileType.Value.String() == ft.String() {
return true
}
}
return false
}
const (
// FileTypeJson json格式文件
FileTypeJson = "json"
// FileTypeIni ini格式文件
FileTypeIni = "ini"
// FileTypeYml yml 格式文件
FileTypeYml = "yml"
// FileTypeYaml yaml格式文件
FileTypeYaml = "yaml"
// FileTypeToml toml格式文件
FileTypeToml = "toml"
// FileTypeXml xml格式文件
FileTypeXml = "xml"
// FileTypeTxt txt格式文件
FileTypeTxt = "txt"
// FileTypeUnknown 文职格式文件
FileTypeUnknown = "unknown"
FileTypeJson FileType = "json" // json格式文件
FileTypeIni FileType = "ini" // ini格式文件
FileTypeYml FileType = "yml" // yml 格式文件
FileTypeYaml FileType = "yaml" // yaml格式文件
FileTypeToml FileType = "toml" // toml格式文件
FileTypeXml FileType = "xml" // xml格式文件
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)
})
}

25
gin.go Normal file
View File

@ -0,0 +1,25 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-07-23 16:46
package consts
const (
GinRequestIDField = "request_id" // 请求ID
GinTraceIDField = "trace_id" // 追踪ID
GinStartRequestTimeField = "start_request_time" // 开始请求时间字段
GinFinishRequestTimeField = "finish_request_time" // 开始请求时间字段
GinResponseCodeField = "code" // 响应状态码字段
GinResponseMessageField = "message" // 响应信息字段
GinHandleRequestCostField = "cost" // 处理请求耗时字段
GinResponseDataField = "data" // 响应数据字段
GinResponseTraceIDField = "trace_id" // 响应TraceID字段
GinResponseRequestIDField = "request_id" // 响应的请求ID字段
GinRecordResponseDataField = "record_response_data" // 记录响应数据到上下文
GinRecordRequestDataField = "record_request_data" // 记录请求数据到上下文
GinRequestIsSuccessField = "request_is_success" // 请求是否成功
GinResponseExtensionField = "extension_data" // 扩展数据字段
)

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

@ -7,10 +7,35 @@
// Date : 2024-01-04 20:28
package consts
type HttpHeader string
func (hh HttpHeader) String() string {
return string(hh)
}
func (hh HttpHeader) MarshalJSON() ([]byte, error) {
return []byte(`"` + hh.String() + `"`), nil
}
const (
HeaderKeyAccessControlAllowOrigin = "Access-Control-Allow-Origin" // 标识允许哪个域的请求
HeaderKeyAccessControlAllowHeaders = "Access-Control-Allow-Headers" // 标识允许的请求header
HeaderKeyAccessControlAllowMethods = "Access-Control-Allow-Methods" // 标识允许的请求方法
HeaderKeyAccessControlExposeHeaders = "Access-Control-Expose-Headers" // 允许浏览器端能够获取相应的header值
HeaderKeyAccessControlMaxAge = "Access-Control-Max-Age" // 控制发送预检请求options的频率单位 : 秒
HeaderKeyAccessControlAllowOrigin HttpHeader = "Access-Control-Allow-Origin" // 标识允许哪个域的请求
HeaderKeyAccessControlAllowHeaders HttpHeader = "Access-Control-Allow-Headers" // 标识允许的请求header
HeaderKeyAccessControlAllowMethods HttpHeader = "Access-Control-Allow-Methods" // 标识允许的请求方法
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)
})
}

13
linux.go Normal file
View File

@ -0,0 +1,13 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-06-24 12:08
package consts
const (
LinuxMaxPort = 65535 // 最大端口号
LinuxMinPort = 80 // 最小端口号
)

129
logger.go Normal file
View File

@ -0,0 +1,129 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-06-24 15:46
package consts
type LogLevel string
func (ll LogLevel) String() string {
return string(ll)
}
func (ll LogLevel) MarshalJSON() ([]byte, error) {
return []byte(`"` + ll.String() + `"`), nil
}
func (ll LogLevel) IsValid() bool {
levelList := []LogLevel{
LogLevelDebug,
LogLevelInfo,
LogLevelWarn,
LogLevelError,
LogLevelPanic,
}
for _, level := range levelList {
if level == ll {
return true
}
}
return false
}
const (
LogLevelDebug LogLevel = "DEBUG"
LogLevelInfo LogLevel = "INFO"
LogLevelWarn LogLevel = "WARN"
LogLevelError LogLevel = "ERROR"
LogLevelPanic LogLevel = "PANIC"
)
type LogSplit string
func (ls LogSplit) String() string {
return string(ls)
}
func (ls LogSplit) MarshalJSON() ([]byte, error) {
return []byte(`"` + ls.String() + `"`), nil
}
func (ls LogSplit) IsValid() bool {
for _, supportSplit := range SupportLogSplitList {
if supportSplit.Value == ls || supportSplit.Value.String() == ls.String() {
return true
}
}
return false
}
const (
LogSplitHour LogSplit = "HOUR"
LogSplitDay LogSplit = "DAY"
LogSplitMonth LogSplit = "MONTH"
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"
)
const (
LogMessageKey = "message"
LogLevelKey = "level"
LogTimeKey = "time"
LogCallerKey = "caller"
)
const (
LogAccessName = "access.log"
LogRequestName = "request.log"
LogProxyName = "proxy.log"
LogBusinessName = "business.log"
LogMonitorName = "monitor.log"
LogDatabaseName = "database.log"
LogRateLimitName = "rate-limit.log"
LogEventName = "event.log"
LogCacheName = "cache.log"
)
const (
LogTypeAccess = "access" // 访问日志
LogTypeRequest = "request" // 请求日志
LogTypeOutput = "output" // 响应日志
LogTypeProxy = "proxy" // 代理请求日志
LogTypeBusiness = "business" // 业务日志
LogTypeMonitor = "monitor" // 监控日志
LogTypeDatabase = "database" // 数据库日志
LogTypeRateLimit = "rate-limit" // 流控日志
LogTypeEvent = "event" // 事件日志
LogTypeCache = "cache" // 缓存日志
)

68
logger_test.go Normal file
View File

@ -0,0 +1,68 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-01-22 15:36
package consts
import (
"encoding/json"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestLogLevel_String(t *testing.T) {
Convey("logger type字符串值", t, func() {
byteData, err := json.Marshal(LogLevelDebug)
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,8 +96,12 @@ 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 "
MimeTypeXWWWFormUrlencoded = "application/x-www-form-urlencoded"
// MimeTypeXml xml请求方式
MimeTypeXml = "application/xml"
// MimeTypeAcc acc音频
MimeTypeAcc = "audio/acc"
// MimeTypeAbw .abw后缀的文件

49
redis.go Normal file
View File

@ -0,0 +1,49 @@
// Package consts ...
//
// Description : consts ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-10-08 16:32
package consts
type RedisCmd string
func (rc RedisCmd) String() string {
return string(rc)
}
func (rc RedisCmd) MarshalJSON() ([]byte, error) {
return []byte(`"` + rc.String() + `"`), nil
}
func (rc RedisCmd) MarshalBinary() ([]byte, error) {
return []byte(rc.String()), nil
}
const (
RedisCommandExists RedisCmd = "EXISTS"
RedisCommandTTL RedisCmd = "TTL"
RedisCommandSet RedisCmd = "SET"
RedisCommandDel RedisCmd = "DEL"
RedisCommandGet RedisCmd = "GET"
RedisCommandHget RedisCmd = "HGET"
RedisCommandHset RedisCmd = "HSET"
RedisCommandHdel RedisCmd = "HDEL"
RedisCommandMGet RedisCmd = "MGET"
RedisCommandMSet RedisCmd = "MSET"
RedisCommandLpush RedisCmd = "LPUSH"
RedisCommandLpop RedisCmd = "LPOP"
RedisCommandRpush RedisCmd = "RPUSH"
RedisCommandRpop RedisCmd = "RPOP"
RedisCommandSadd RedisCmd = "SADD"
RedisCommandSunionstore RedisCmd = "SUNIONSTORE"
RedisCommandZadd RedisCmd = "ZADD"
RedisCommandZincrby RedisCmd = "ZINCRBY"
RedisCommandPsubScribe RedisCmd = "PSUBSCRIBE"
RedisCommandPubsub RedisCmd = "PUBSUB"
RedisCommandPublish RedisCmd = "PUBLISH"
RedisCommandPunsubScribe RedisCmd = "PUNSUBSCRIBE"
RedisCommandSubscribe RedisCmd = "SUBSCRIBE"
RedisCommandUnsubscribe RedisCmd = "UNSUBSCRIBE"
)

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

@ -7,10 +7,99 @@
// Date : 2024-04-22 11:04
package consts
// RequestDataLocation 请求数据所在位置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:40 2024/11/25
type RequestDataLocation string
func (rdl RequestDataLocation) String() string {
return string(rdl)
}
func (rdl RequestDataLocation) MarshalJSON() ([]byte, error) {
return []byte(`"` + rdl.String() + `"`), nil
}
func (rdl RequestDataLocation) IsValid() bool {
for _, item := range RequestDataLocationList {
if item.Value == rdl || item.Value.String() == rdl.String() {
return true
}
}
return false
}
const (
RequestLocationHeader = "HEADER" // header
RequestLocationCookie = "COOKIE" // cookie
RequestLocationBody = "BODY" // body
RequestLocationQuery = "QUERY" // query
RequestLocationUriPath = "URI_PATH" // uri路由一部分
RequestDataLocationHeader RequestDataLocation = "HEADER" // header
RequestDataLocationCookie RequestDataLocation = "COOKIE" // cookie
RequestDataLocationBody RequestDataLocation = "BODY" // body
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
ResponseDataLocationBody ResponseDataLocation = "BODY" // body
ResponseDataLocationExtension ResponseDataLocation = "EXTENSION" // 扩展信息
ResponseDataLocationBodyRoot ResponseDataLocation = "BODY_ROOT" // 整个body是当前值
)
type RequestDataLocationDesc struct {
Value RequestDataLocation `json:"value"` // 数据位置
Description string `json:"description"` // 数据位置描述
}
type ResponseDataLocationDesc struct {
Value ResponseDataLocation `json:"value"` // 数据位置
Description string `json:"description"` // 数据位置描述
}
var (
RequestDataLocationList = []RequestDataLocationDesc{
{Value: RequestDataLocationHeader, Description: "请求header"},
{Value: RequestDataLocationCookie, Description: "请求cookie"},
{Value: RequestDataLocationBody, Description: "请求body"},
{Value: RequestDataLocationQuery, Description: "请求query"},
{Value: RequestDataLocationUriPath, Description: "请求uri_path"},
{Value: RequestDataLocationAny, Description: "任意位置,要求服务本身支持"},
{Value: RequestDataLocationStatic, Description: "静态参数配置"},
{Value: RequestDataLocationCustomConfig, Description: "自定义接口处理规则"},
}
ResponseDataLocationList = []ResponseDataLocationDesc{
{Value: ResponseDataLocationHeader, Description: "响应header"},
{Value: ResponseDataLocationCookie, Description: "响应cookie"},
{Value: ResponseDataLocationBody, Description: "响应body"},
{Value: ResponseDataLocationExtension, Description: "响应扩展数据"},
{Value: ResponseDataLocationBodyRoot, Description: "相应整体Body"},
}
)

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

@ -7,32 +7,42 @@
// Date : 2024-01-01 14:33
package consts
const (
SchemeHTTP = "http"
SchemeHTTPS = "https"
SchemeWs = "ws"
SchemeWss = "wss"
type HttpScheme string
SchemeSms = "sms" // SchemeSms 短信
SchemeTel = "tel" // SchemeTel 电话
SchemeMobileNotes = "mobilenotes" // SchemeMobileNotes 备忘录
SchemeMessage = "MESSAGE" // SchemeMessage E-MAIL
func (hs HttpScheme) String() string {
return string(hs)
}
SchemeAliPay = "alipay" // SchemeAliPay 支付宝
SchemeDingTalk = "dingtalk" // SchemeDingTalk 钉钉
SchemeWeChat = "wechat" // SchemeWeChat 微信
SchemeWeiXin = "weixin" // SchemeWeiXin 微信
func (hs HttpScheme) MarshalJSON() ([]byte, error) {
return []byte(`"` + hs.String() + `"`), nil
}
SchemeTCP = "tcp"
SchemeUDP = "udp"
SchemeUnix = "unix"
SchemeKCP = "kcp"
SchemeQuic = "quic"
SchemeGRPC = "grpc"
SchemeMQTT = "mqtt"
SchemeMQTT5 = "mqtt5"
SchemeMQTTN = "mqttn"
SchemeMQTTv3 = "mqttv3"
SchemeMQTTv4 = "mqttv4"
SchemeMQTTv5 = "mqttv5"
var (
SchemeHTTP HttpScheme = "http"
SchemeHTTPS HttpScheme = "https"
SchemeWs HttpScheme = "ws"
SchemeWss HttpScheme = "wss"
SchemeSms HttpScheme = "sms" // SchemeSms 短信
SchemeTel HttpScheme = "tel" // SchemeTel 电话
SchemeMobileNotes HttpScheme = "mobilenotes" // SchemeMobileNotes 备忘录
SchemeMessage HttpScheme = "MESSAGE" // SchemeMessage E-MAIL
SchemeAliPay HttpScheme = "alipay" // SchemeAliPay 支付宝
SchemeDingTalk HttpScheme = "dingtalk" // SchemeDingTalk 钉钉
SchemeWeChat HttpScheme = "wechat" // SchemeWeChat 微信
SchemeWeiXin HttpScheme = "weixin" // SchemeWeiXin 微信
SchemeTCP HttpScheme = "tcp"
SchemeUDP HttpScheme = "udp"
SchemeUnix HttpScheme = "unix"
SchemeKCP HttpScheme = "kcp"
SchemeQuic HttpScheme = "quic"
SchemeGRPC HttpScheme = "grpc"
SchemeMQTT HttpScheme = "mqtt"
SchemeMQTT5 HttpScheme = "mqtt5"
SchemeMQTTN HttpScheme = "mqttn"
SchemeMQTTv3 HttpScheme = "mqttv3"
SchemeMQTTv4 HttpScheme = "mqttv4"
SchemeMQTTv5 HttpScheme = "mqttv5"
)

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

@ -8,18 +8,24 @@
package consts
const (
SwaggerDataTypeInteger = "integer"
SwaggerDataTypeNumber = "number"
SwaggerDataTypeString = "string"
SwaggerDataTypeBoolean = "boolean"
SwaggerDataTypeArray = "array"
SwaggerDataTypeObject = "object"
SwaggerDataTypeInteger = "integer" // 32 位有符号
SwaggerDataTypeLong = "long" // 64 位有符号
SwaggerDataTypeFloat = "number"
SwaggerDataTypeDouble = "number"
SwaggerDataTypeNumber = "number"
SwaggerDataTypeByte = "string"
SwaggerDataTypeBinary = "binary" // 任意 8 进制序列
SwaggerDataTypeString = "string"
SwaggerDataTypeDate = "string"
SwaggerDataTypePassword = "password"
SwaggerDataTypeBoolean = "boolean"
SwaggerDataTypeArray = "array"
SwaggerDataTypeObject = "object"
)
const (
SwaggerDocVersion1 = "1.0"
SwaggerDocVersion2 = "2.0"
SwaggerDocVersion3 = "3.0"
SwaggerDocVersion3 = "3.0.0"
)
const (
@ -34,3 +40,20 @@ const (
const (
SwaggerBaseObjectDefinitionName = "object_map"
)
const (
SwaggerParameterInQuery = "query" // 参数位置 : query
SwaggerParameterInHeader = "header" // 参数位置 : header
SwaggerParameterInPath = "path" // 参数位置 : path
SwaggerParameterInCookie = "cookie" // 参数位置 : cookie
)
const (
SwaggerParameterStyleForm = "form" // in = query / cookie , type = primitive, array, object
SwaggerParameterStyleSimple = "simple" // in = path / header , type = array , Simple 样式的参数,参见 RFC6570. 此选项替换定义于OpenAPI 2.0 中 collectionFormat等于csv的情况。
SwaggerParameterStyleMatrix = "matrix" // in = path type = primitive, array, object
SwaggerParameterStyleLabel = "label" // in = path , type = primitive, array, object
SwaggerParameterStyleSpaceDelimited = "spaceDelimited" // in = query , type = array, 空格分隔的数组值。此选项替换定义于OpenAPI 2.0 中 collectionFormat equal to ssv的情况。
SwaggerParameterStylePipeDelimited = "pipeDelimited" // in = query , type = array, 管道符`
SwaggerParameterStyleDeepObject = "deepObject" // in = query , type = object, 提供一种简单的方法来表示参数中的嵌套对象值.`
)

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)
})
}