This commit is contained in:
兔子
2023-08-26 17:36:50 +08:00
parent c088498118
commit 062b2bb768
24 changed files with 294 additions and 448 deletions

View File

@@ -1,136 +1,17 @@
package utils package utils
import "net/url"
func init() { func init() {
Is.Ip = IsIp
Is.Url = IsUrl
Is.Email = IsEmail
Is.Phone = IsPhone
Is.Mobile = IsMobile
Is.Empty = IsEmpty
Is.True = IsTrue
Is.False = IsFalse
Is.Number = IsNumber
Is.Float = IsFloat
Is.Bool = IsBool
Is.Accepted = IsAccepted
Is.Date = IsDate
Is.Alpha = IsAlpha
Is.AlphaNum = IsAlphaNum
Is.AlphaDash = IsAlphaDash
Is.Chs = IsChs
Is.ChsAlpha = IsChsAlpha
Is.ChsAlphaNum = IsChsAlphaNum
Is.ChsDash = IsChsDash
Is.Cntrl = IsCntrl
Is.Graph = IsGraph
Is.Lower = IsLower
Is.Upper = IsUpper
Is.Space = IsSpace
Is.Xdigit = IsXdigit
Is.ActiveUrl = IsActiveUrl
Is.Domain = IsDomain
Is.IdCard = IsIdCard
Is.MacAddr = IsMacAddr
Is.Zip = IsZip
Is.String = IsString
Is.Slice = IsSlice
Is.Array = IsArray
Is.JsonString = IsJsonString
Is.Map = IsMap
Is.SliceSlice = IsSliceSlice
Is.MapAny = IsMapAny
Get.Type = GetType
Get.Ip = GetIp
Get.Mac = GetMac
Get.Pid = GetPid
Get.Pwd = GetPwd
In.Array = InArray[any] In.Array = InArray[any]
Array.Filter = ArrayFilter Array.Filter = ArrayFilter
Array.Remove = ArrayRemove Array.Remove = ArrayRemove
Array.Unique = ArrayUnique[any] Array.Unique = ArrayUnique[any]
Array.Empty = ArrayEmpty[any] Array.Empty = ArrayEmpty[any]
Array.MapWithField = ArrayMapWithField Array.MapWithField = ArrayMapWithField
Password.Create = PasswordCreate
Password.Verify = PasswordVerify
Struct.Set = StructSet
Struct.Get = StructGet
Struct.Del = StructDel
Struct.Has = StructHas
Struct.Keys = StructKeys
Struct.Values = StructValues
Struct.Len = StructLen
Struct.Map = StructMap
Struct.Slice = StructSlice
Json.Encode = JsonEncode
Json.Decode = JsonDecode
Json.Get = JsonGet
Json.String = JsonString
Format.Query = FormatQuery
Parse.ParamsBefore = ParseParamsBefore
Parse.Params = ParseParams
Parse.Domain = ParseDomain
Net.Tcping = NetTcping
Mime.Type = MimeType
Map.WithField = MapWithField[map[string]any] Map.WithField = MapWithField[map[string]any]
Map.WithoutField = MapWithoutField[map[string]any] Map.WithoutField = MapWithoutField[map[string]any]
Map.ToURL = MapToURL Map.ToURL = MapToURL
Map.Keys = MapKeys[map[string]any] Map.Keys = MapKeys[map[string]any]
Map.Values = MapValues[map[string]any] Map.Values = MapValues[map[string]any]
Version.Go = VersionGo
Version.Compare = VersionCompare
Unity.Ids = UnityIds
Unity.Keys = UnityKeys
}
var Is struct {
Ip func(ip any) (ok bool)
Url func(url any) (ok bool)
Email func(email any) (ok bool)
Phone func(phone any) (ok bool)
Mobile func(mobile any) (ok bool)
Empty func(value any) (ok bool)
True func(value any) (ok bool)
False func(value any) (ok bool)
Number func(value any) (ok bool)
Float func(value any) (ok bool)
Bool func(value any) (ok bool)
Accepted func(value any) (ok bool)
Date func(date any) (ok bool)
Alpha func(value any) (ok bool)
AlphaNum func(value any) (ok bool)
AlphaDash func(value any) (ok bool)
Chs func(value any) (ok bool)
ChsAlpha func(value any) (ok bool)
ChsAlphaNum func(value any) (ok bool)
ChsDash func(value any) (ok bool)
Cntrl func(value any) (ok bool)
Graph func(value any) (ok bool)
Lower func(value any) (ok bool)
Upper func(value any) (ok bool)
Space func(value any) (ok bool)
Xdigit func(value any) (ok bool)
ActiveUrl func(value any) (ok bool)
Domain func(domain any) (ok bool)
IdCard func(value any) (ok bool)
MacAddr func(value any) (ok bool)
Zip func(value any) (ok bool)
String func(value any) (ok bool)
Slice func(value any) (ok bool)
Array func(value any) (ok bool)
JsonString func(value any) (ok bool)
Map func(value any) (ok bool)
SliceSlice func(value any) (ok bool)
MapAny func(value any) (ok bool)
}
var Get struct {
Type func(value any) (result string)
Ip func(key ...string) (result any)
Mac func() (result string)
Pid func() (result int)
Pwd func() (result string)
} }
var In struct { var In struct {
@@ -145,48 +26,6 @@ var Array struct {
MapWithField func(array []map[string]any, field any) (slice []any) MapWithField func(array []map[string]any, field any) (slice []any)
} }
var Password struct {
Create func(password any) (result string)
Verify func(encode any, password any) (ok bool)
}
var Struct struct {
Set func(obj any, key string, val any)
Get func(obj any, key string) (result any)
Del func(obj any, key string)
Has func(obj any, key string) (ok bool)
Keys func(obj any) (slice []string)
Values func(obj any) (slice []any)
Len func(obj any) (length int)
Map func(obj any) (result map[string]any)
Slice func(obj any) (slice []any)
}
var Json struct {
Encode func(value any) (result string)
Decode func(value any) (result any)
Get func(value any, key any) (result any, err error)
String func(value any) (result string)
}
var Format struct {
Query func(data any) (result string)
}
var Parse struct {
ParamsBefore func(params url.Values) (result map[string]any)
Params func(params map[string]any) (result map[string]any)
Domain func(value any) (domain string)
}
var Net struct {
Tcping func(host any, opts ...map[string]any) (ok bool, detail []map[string]any)
}
var Mime struct {
Type func(suffix any) (mime string)
}
var Map struct { var Map struct {
WithField func(data map[string]any, field []string) (result map[string]any) WithField func(data map[string]any, field []string) (result map[string]any)
WithoutField func(data map[string]any, field []string) (result map[string]any) WithoutField func(data map[string]any, field []string) (result map[string]any)
@@ -194,13 +33,3 @@ var Map struct {
Keys func(data map[string]any) (result []string) Keys func(data map[string]any) (result []string)
Values func(data map[string]any) (result []any) Values func(data map[string]any) (result []any)
} }
var Version struct {
Go func() (version string)
Compare func(v1 any, v2 any) (result int)
}
var Unity struct {
Ids func(param ...any) (result []any)
Keys func(param any, reg ...any) (result []any)
}

View File

@@ -46,7 +46,7 @@ func ArrayUnique[T any](array []T) (slice []any) {
// ArrayEmpty - 数组去空 // ArrayEmpty - 数组去空
func ArrayEmpty[T any](array []T) (slice []any) { func ArrayEmpty[T any](array []T) (slice []any) {
for _, item := range array { for _, item := range array {
if !IsEmpty(item) { if !Is.Empty(item) {
slice = append(slice, item) slice = append(slice, item)
} }
} }
@@ -59,7 +59,7 @@ func ArrayMapWithField(array []map[string]any, field any) (slice []any) {
// 获取字段 // 获取字段
keys := cast.ToStringSlice(Unity.Keys(field)) keys := cast.ToStringSlice(Unity.Keys(field))
if IsEmpty(keys) { if Is.Empty(keys) {
return cast.ToSlice(array) return cast.ToSlice(array)
} }

View File

@@ -10,7 +10,7 @@ type AsyncStruct[T any] struct {
// 读写锁 // 读写锁
Mutex sync.RWMutex Mutex sync.RWMutex
// 等待组 // 等待组
Wait sync.WaitGroup Wait sync.WaitGroup
// 数据 // 数据
Data T Data T
} }
@@ -30,8 +30,8 @@ func Async[T any]() *AsyncStruct[T] {
return &AsyncStruct[T]{ return &AsyncStruct[T]{
Mutex: sync.RWMutex{}, Mutex: sync.RWMutex{},
Wait : sync.WaitGroup{}, Wait: sync.WaitGroup{},
Data : data, Data: data,
} }
} }
@@ -41,7 +41,7 @@ func (this *AsyncStruct[T]) Get(key string) any {
defer this.Mutex.Unlock() defer this.Mutex.Unlock()
this.Mutex.Lock() this.Mutex.Lock()
if IsEmpty(this.Data) { if Is.Empty(this.Data) {
return nil return nil
} }
@@ -84,7 +84,7 @@ func (this *AsyncStruct[T]) Has(key string) (ok bool) {
defer this.Mutex.Unlock() defer this.Mutex.Unlock()
this.Mutex.Lock() this.Mutex.Lock()
if IsEmpty(this.Data) { if Is.Empty(this.Data) {
return false return false
} }

View File

@@ -26,7 +26,7 @@ func Ternary[T any](IF bool, TRUE T, FALSE T) T {
// Default - 设置默认值 // Default - 设置默认值
func Default[T any](param T, value ...T) (result T) { func Default[T any](param T, value ...T) (result T) {
if IsEmpty(param) { if Is.Empty(param) {
if len(value) > 0 { if len(value) > 0 {
return value[0] return value[0]
} }

View File

@@ -124,7 +124,7 @@ func (this *FileCacheClient) Set(key any, value []byte, expire ...any) (ok bool)
exp := this.expire exp := this.expire
if len(expire) > 0 { if len(expire) > 0 {
if !IsEmpty(expire[0]) { if !Is.Empty(expire[0]) {
// 判断 expire[0] 是否为Duration类型 // 判断 expire[0] 是否为Duration类型
if reflect.TypeOf(expire[0]).String() == "time.Duration" { if reflect.TypeOf(expire[0]).String() == "time.Duration" {
// 转换为int64 // 转换为int64

View File

@@ -48,23 +48,23 @@ func Curl(request ...CurlRequest) *CurlStruct {
request = append(request, CurlRequest{}) request = append(request, CurlRequest{})
} }
if IsEmpty(request[0].Method) { if Is.Empty(request[0].Method) {
request[0].Method = "GET" request[0].Method = "GET"
} }
if IsEmpty(request[0].Data) { if Is.Empty(request[0].Data) {
request[0].Data = make(map[string]any) request[0].Data = make(map[string]any)
} }
if IsEmpty(request[0].Query) { if Is.Empty(request[0].Query) {
request[0].Query = make(map[string]any) request[0].Query = make(map[string]any)
} }
if IsEmpty(request[0].Headers) { if Is.Empty(request[0].Headers) {
request[0].Headers = make(map[string]any) request[0].Headers = make(map[string]any)
} }
if IsEmpty(request[0].Client) { if Is.Empty(request[0].Client) {
request[0].Client = &http.Client{} request[0].Client = &http.Client{}
} }
@@ -180,7 +180,7 @@ func (this *CurlStruct) Client(client *http.Client) *CurlStruct {
// Send - 发起请求 // Send - 发起请求
func (this *CurlStruct) Send() *CurlResponse { func (this *CurlStruct) Send() *CurlResponse {
if IsEmpty(this.request.Url) { if Is.Empty(this.request.Url) {
this.response.Error = errors.New("url is required") this.response.Error = errors.New("url is required")
return this.response return this.response
} }
@@ -209,8 +209,8 @@ func (this *CurlStruct) Send() *CurlResponse {
// buffer, _ = json.Marshal(this.request.Body) // buffer, _ = json.Marshal(this.request.Body)
// 如果 this.request.Body 是 map 类型,则直接转换为 json // 如果 this.request.Body 是 map 类型,则直接转换为 json
if IsMap(this.request.Body) { if Is.Map(this.request.Body) {
buffer = []byte(JsonEncode(this.request.Body)) buffer = []byte(Json.Encode(this.request.Body))
} else { } else {
buffer = []byte(cast.ToString(this.request.Body)) buffer = []byte(cast.ToString(this.request.Body))
} }
@@ -305,7 +305,7 @@ func (this *CurlStruct) Send() *CurlResponse {
this.response.Text = string(body) this.response.Text = string(body)
this.response.Headers = &response.Header this.response.Headers = &response.Header
this.response.Request = response.Request this.response.Request = response.Request
this.response.Json = cast.ToStringMap(JsonDecode(string(body))) this.response.Json = cast.ToStringMap(Json.Decode(string(body)))
this.response.StatusCode = response.StatusCode this.response.StatusCode = response.StatusCode
return this.response return this.response

View File

@@ -59,23 +59,23 @@ func File(request ...FileRequest) *FileStruct {
request = append(request, FileRequest{}) request = append(request, FileRequest{})
} }
if IsEmpty(request[0].Limit) { if Is.Empty(request[0].Limit) {
request[0].Limit = 10 request[0].Limit = 10
} }
if IsEmpty(request[0].Page) { if Is.Empty(request[0].Page) {
request[0].Page = 1 request[0].Page = 1
} }
if IsEmpty(request[0].Format) { if Is.Empty(request[0].Format) {
request[0].Format = "network" request[0].Format = "network"
} }
if IsEmpty(request[0].Sub) { if Is.Empty(request[0].Sub) {
request[0].Sub = true request[0].Sub = true
} }
if IsEmpty(request[0].Ext) { if Is.Empty(request[0].Ext) {
request[0].Ext = "*" request[0].Ext = "*"
} }
@@ -140,7 +140,7 @@ func (this *FileStruct) Save(reader io.Reader, path ...string) (result *FileResp
this.request.Path = path[0] this.request.Path = path[0]
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("文件路径不能为空") this.response.Error = errors.New("文件路径不能为空")
return this.response return this.response
} }
@@ -187,7 +187,7 @@ func (this *FileStruct) Remove(path ...any) (result *FileResponse) {
this.request.Path = cast.ToString(path[0]) this.request.Path = cast.ToString(path[0])
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("文件路径不能为空") this.response.Error = errors.New("文件路径不能为空")
return this.response return this.response
} }
@@ -236,7 +236,7 @@ func (this *FileStruct) Download(path ...any) (result *FileResponse) {
this.request.Path = cast.ToString(path[0]) this.request.Path = cast.ToString(path[0])
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("文件路径不能为空") this.response.Error = errors.New("文件路径不能为空")
return this.response return this.response
} }
@@ -256,7 +256,7 @@ func (this *FileStruct) Download(path ...any) (result *FileResponse) {
} }
defer resp.Body.Close() defer resp.Body.Close()
if IsEmpty(this.request.Name) { if Is.Empty(this.request.Name) {
this.request.Name = filepath.Base(this.request.Path) this.request.Name = filepath.Base(this.request.Path)
} }
@@ -299,7 +299,7 @@ func (this *FileStruct) Byte(path ...any) (result *FileResponse) {
this.request.Path = cast.ToString(path[0]) this.request.Path = cast.ToString(path[0])
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("文件路径不能为空") this.response.Error = errors.New("文件路径不能为空")
return this.response return this.response
} }
@@ -368,7 +368,7 @@ func (this *FileStruct) List(path ...any) (result *FileResponse) {
this.request.Path = cast.ToString(path[0]) this.request.Path = cast.ToString(path[0])
} }
if IsEmpty(this.request.Dir) { if Is.Empty(this.request.Dir) {
this.response.Error = errors.New("目录路径不能为空") this.response.Error = errors.New("目录路径不能为空")
return this.response return this.response
} }
@@ -388,7 +388,7 @@ func (this *FileStruct) List(path ...any) (result *FileResponse) {
// this.request.Ext 逗号分隔的字符串 转 []string // this.request.Ext 逗号分隔的字符串 转 []string
for _, val := range strings.Split(this.request.Ext, ",") { for _, val := range strings.Split(this.request.Ext, ",") {
// 忽略空字符串 // 忽略空字符串
if IsEmpty(val) { if Is.Empty(val) {
continue continue
} }
// 去除空格 // 去除空格
@@ -406,7 +406,7 @@ func (this *FileStruct) List(path ...any) (result *FileResponse) {
if this.request.Format == "network" { if this.request.Format == "network" {
for key, val := range slice { for key, val := range slice {
slice[key] = filepath.ToSlash(val) slice[key] = filepath.ToSlash(val)
if !IsEmpty(this.request.Domain) { if !Is.Empty(this.request.Domain) {
slice[key] = this.request.Domain + slice[key][len(this.request.Prefix):] slice[key] = this.request.Domain + slice[key][len(this.request.Prefix):]
} }
} }
@@ -429,7 +429,7 @@ func (this *FileStruct) Exist(path ...any) (ok bool) {
this.request.Path = cast.ToString(path[0]) this.request.Path = cast.ToString(path[0])
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
return false return false
} }
@@ -448,7 +448,7 @@ func (this *FileStruct) Line(path ...any) (result *FileResponse) {
this.request.Path = cast.ToString(path[0]) this.request.Path = cast.ToString(path[0])
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("文件路径不能为空") this.response.Error = errors.New("文件路径不能为空")
return this.response return this.response
} }
@@ -529,7 +529,7 @@ func (this *FileStruct) Line(path ...any) (result *FileResponse) {
wg.Wait() wg.Wait()
this.response.Result = lines this.response.Result = lines
this.response.Text = JsonEncode(this.response.Result) this.response.Text = Json.Encode(this.response.Result)
this.response.Byte = []byte(this.response.Text) this.response.Byte = []byte(this.response.Text)
for _, v := range lines { for _, v := range lines {
@@ -546,7 +546,7 @@ func (this *FileStruct) DirInfo(dir ...any) (result *FileResponse) {
this.request.Dir = cast.ToString(dir[0]) this.request.Dir = cast.ToString(dir[0])
} }
if IsEmpty(this.request.Dir) { if Is.Empty(this.request.Dir) {
this.request.Dir = "./" this.request.Dir = "./"
} }
@@ -597,7 +597,7 @@ func (this *FileStruct) DirInfo(dir ...any) (result *FileResponse) {
"dirs": dirs, "dirs": dirs,
"files": files, "files": files,
} }
this.response.Text = JsonEncode(this.response.Result) this.response.Text = Json.Encode(this.response.Result)
this.response.Byte = []byte(this.response.Text) this.response.Byte = []byte(this.response.Text)
return this.response return this.response
@@ -616,12 +616,12 @@ func (this *FileStruct) DirInfo(dir ...any) (result *FileResponse) {
*/ */
func (this *FileStruct) EnZip() (result *FileResponse) { func (this *FileStruct) EnZip() (result *FileResponse) {
if IsEmpty(this.request.Dir) { if Is.Empty(this.request.Dir) {
this.response.Error = errors.New("压缩目录不能为空") this.response.Error = errors.New("压缩目录不能为空")
return this.response return this.response
} }
if IsEmpty(this.request.Path) && !IsEmpty(this.request.Name) { if Is.Empty(this.request.Path) && !Is.Empty(this.request.Name) {
// 判断 Dir 是否以 / 结尾 // 判断 Dir 是否以 / 结尾
if this.request.Dir[len(this.request.Dir)-1:] != "/" { if this.request.Dir[len(this.request.Dir)-1:] != "/" {
@@ -636,7 +636,7 @@ func (this *FileStruct) EnZip() (result *FileResponse) {
this.request.Path = this.request.Dir + this.request.Name this.request.Path = this.request.Dir + this.request.Name
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("压缩后的文件路径不能为空") this.response.Error = errors.New("压缩后的文件路径不能为空")
return this.response return this.response
} }
@@ -745,12 +745,12 @@ func (this *FileStruct) EnZip() (result *FileResponse) {
*/ */
func (this *FileStruct) UnZip() (result *FileResponse) { func (this *FileStruct) UnZip() (result *FileResponse) {
if IsEmpty(this.request.Dir) { if Is.Empty(this.request.Dir) {
this.response.Error = errors.New("解压路径不能为空") this.response.Error = errors.New("解压路径不能为空")
return this.response return this.response
} }
if IsEmpty(this.request.Path) && !IsEmpty(this.request.Name) { if Is.Empty(this.request.Path) && !Is.Empty(this.request.Name) {
// 判断 Dir 是否以 / 结尾 // 判断 Dir 是否以 / 结尾
if this.request.Dir[len(this.request.Dir)-1:] != "/" { if this.request.Dir[len(this.request.Dir)-1:] != "/" {
@@ -765,7 +765,7 @@ func (this *FileStruct) UnZip() (result *FileResponse) {
this.request.Path = this.request.Dir + this.request.Name this.request.Path = this.request.Dir + this.request.Name
} }
if IsEmpty(this.request.Path) { if Is.Empty(this.request.Path) {
this.response.Error = errors.New("压缩包路径不能为空") this.response.Error = errors.New("压缩包路径不能为空")
return this.response return this.response
} }
@@ -797,39 +797,6 @@ func (this *FileStruct) UnZip() (result *FileResponse) {
this.response.Error = err this.response.Error = err
return this.response return this.response
} }
// item, err := file.Open()
// if err != nil {
// this.response.Error = err
// return this.response
// }
// defer func(item io.ReadCloser) {
// err := item.Close()
// if err != nil {
// this.response.Error = err
// return
// }
// }(item)
//
// Byte, err := io.ReadAll(item)
// if err != nil {
// this.response.Error = err
// return this.response
// }
//
// // 如果 this.request.Dir 不存在,则创建
// if _, err := os.Stat(this.request.Dir); os.IsNotExist(err) {
// err := os.Mkdir(this.request.Dir, os.ModePerm)
// if err != nil {
// this.response.Error = err
// return this.response
// }
// }
//
// err = os.WriteFile(this.request.Dir+"/"+file.Name, Byte, 0644)
// if err != nil {
// this.response.Error = err
// return this.response
// }
} }
this.response.Text = "1" this.response.Text = "1"

View File

@@ -6,8 +6,12 @@ import (
"strings" "strings"
) )
// FormatQuery 转 Query 格式 var Format *FormatStruct
func FormatQuery(data any) (result string) {
type FormatStruct struct{}
// Query 转 Query 格式
func (this *FormatStruct) Query(data any) (result string) {
body := cast.ToStringMap(data) body := cast.ToStringMap(data)

View File

@@ -9,14 +9,19 @@ import (
"sync" "sync"
) )
// GetType - 获取数据类型 // Get - 获取
func GetType(value any) (result string) { var Get *GetStruct
type GetStruct struct{}
// Type - 获取数据类型
func (this *GetStruct) Type(value any) (result string) {
result, _ = typeof(value) result, _ = typeof(value)
return result return result
} }
// GetIp - 获取客户端IP // Ip - 获取客户端IP
func GetIp(key ...string) (result any) { func (this *GetStruct) Ip(key ...string) (result any) {
type lock struct { type lock struct {
Lock *sync.RWMutex Lock *sync.RWMutex
@@ -66,8 +71,8 @@ func GetIp(key ...string) (result any) {
return wr.Data return wr.Data
} }
// GetMac - 获取本机MAC // Mac - 获取本机MAC
func GetMac() (result string) { func (this *GetStruct) Mac() (result string) {
interfaces, err := net.Interfaces() interfaces, err := net.Interfaces()
@@ -93,8 +98,8 @@ func GetMac() (result string) {
return "" return ""
} }
// GetPid - 获取进程ID // Pid - 获取进程ID
func GetPid() (result int) { func (this *GetStruct) Pid() (result int) {
process, err := os.FindProcess(os.Getpid()) process, err := os.FindProcess(os.Getpid())
if err != nil { if err != nil {
return 0 return 0
@@ -102,8 +107,8 @@ func GetPid() (result int) {
return process.Pid return process.Pid
} }
// GetPwd - 获取当前目录 // Pwd - 获取当前目录
func GetPwd() (result string) { func (this *GetStruct) Pwd() (result string) {
dir, err := os.Getwd() dir, err := os.Getwd()
if err != nil { if err != nil {
return "" return ""

View File

@@ -1 +0,0 @@
package utils

View File

@@ -6,293 +6,298 @@ import (
"regexp" "regexp"
) )
// IsEmail - 是否为邮箱 // Is - 是否为
func IsEmail(email any) (ok bool) { var Is *IsStruct
type IsStruct struct{}
// Email - 是否为邮箱
func (this *IsStruct) Email(email any) (ok bool) {
if email == nil { if email == nil {
return false return false
} }
return regexp.MustCompile(`\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}`).MatchString(cast.ToString(email)) return regexp.MustCompile(`\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}`).MatchString(cast.ToString(email))
} }
// IsPhone - 是否为手机号 // Phone - 是否为手机号
func IsPhone(phone any) (ok bool) { func (this *IsStruct) Phone(phone any) (ok bool) {
if phone == nil { if phone == nil {
return false return false
} }
return regexp.MustCompile(`^1[3456789]\d{9}$`).MatchString(cast.ToString(phone)) return regexp.MustCompile(`^1[3456789]\d{9}$`).MatchString(cast.ToString(phone))
} }
// IsMobile - 是否为手机号 // Mobile - 是否为手机号
func IsMobile(value any) (ok bool) { func (this *IsStruct) Mobile(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^1[3456789]\d{9}$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^1[3456789]\d{9}$`).MatchString(cast.ToString(value))
} }
// IsEmpty - 是否为空 // Empty - 是否为空
func IsEmpty(value any) (ok bool) { func (this *IsStruct) Empty(value any) (ok bool) {
_, empty := typeof(value) _, empty := typeof(value)
return empty return empty
} }
// IsDomain - 是否为域名 // Domain - 是否为域名
func IsDomain(domain any) (ok bool) { func (this *IsStruct) Domain(domain any) (ok bool) {
if domain == nil { if domain == nil {
return false return false
} }
return regexp.MustCompile(`^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+`).MatchString(cast.ToString(domain)) return regexp.MustCompile(`^((https|http|ftp|rtsp|mms)?://)\S+`).MatchString(cast.ToString(domain))
} }
// IsTrue - 是否为真 // True - 是否为真
func IsTrue(value any) (ok bool) { func (this *IsStruct) True(value any) (ok bool) {
return cast.ToBool(value) return cast.ToBool(value)
} }
// IsFalse - 是否为假 // False - 是否为假
func IsFalse(value any) (ok bool) { func (this *IsStruct) False(value any) (ok bool) {
return !cast.ToBool(value) return !cast.ToBool(value)
} }
// IsNumber - 是否为数字 // Number - 是否为数字
func IsNumber(value any) (ok bool) { func (this *IsStruct) Number(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[0-9]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[0-9]+$`).MatchString(cast.ToString(value))
} }
// IsFloat - 是否为浮点数 // Float - 是否为浮点数
func IsFloat(value any) (ok bool) { func (this *IsStruct) Float(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[0-9]+(.[0-9]+)?$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[0-9]+(.[0-9]+)?$`).MatchString(cast.ToString(value))
} }
// IsBool - 是否为bool // Bool - 是否为bool
func IsBool(value any) (ok bool) { func (this *IsStruct) Bool(value any) (ok bool) {
return cast.ToBool(value) return cast.ToBool(value)
} }
// IsAccepted - 验证某个字段是否为为 yes, on, 或是 1 // Accepted - 验证某个字段是否为为 yes, on, 或是 1
func IsAccepted(value any) (ok bool) { func (this *IsStruct) Accepted(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^(yes|on|1)$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^(yes|on|1)$`).MatchString(cast.ToString(value))
} }
// IsDate - 是否为日期类型 // Date - 是否为日期类型
func IsDate(date any) (ok bool) { func (this *IsStruct) Date(date any) (ok bool) {
if date == nil { if date == nil {
return false return false
} }
return regexp.MustCompile(`^\d{4}-\d{1,2}-\d{1,2}$`).MatchString(cast.ToString(date)) return regexp.MustCompile(`^\d{4}-\d{1,2}-\d{1,2}$`).MatchString(cast.ToString(date))
} }
// IsAlpha - 只能包含字母 // Alpha - 只能包含字母
func IsAlpha(value any) (ok bool) { func (this *IsStruct) Alpha(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[a-zA-Z]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[a-zA-Z]+$`).MatchString(cast.ToString(value))
} }
// IsAlphaNum - 只能包含字母和数字 // AlphaNum - 只能包含字母和数字
func IsAlphaNum(value any) (ok bool) { func (this *IsStruct) AlphaNum(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString(cast.ToString(value))
} }
// IsAlphaDash - 只能包含字母、数字和下划线_及破折号- // AlphaDash - 只能包含字母、数字和下划线_及破折号-
func IsAlphaDash(value any) (ok bool) { func (this *IsStruct) AlphaDash(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(cast.ToString(value))
} }
// IsChs - 是否为汉字 // Chs - 是否为汉字
func IsChs(value any) (ok bool) { func (this *IsStruct) Chs(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}]+$`).MatchString(cast.ToString(value))
} }
// IsChsAlpha - 只能是汉字、字母 // ChsAlpha - 只能是汉字、字母
func IsChsAlpha(value any) (ok bool) { func (this *IsStruct) ChsAlpha(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z]+$`).MatchString(cast.ToString(value))
} }
// IsChsAlphaNum - 只能是汉字、字母和数字 // ChsAlphaNum - 只能是汉字、字母和数字
func IsChsAlphaNum(value any) (ok bool) { func (this *IsStruct) ChsAlphaNum(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$`).MatchString(cast.ToString(value))
} }
// IsChsDash - 只能是汉字、字母、数字和下划线_及破折号- // ChsDash - 只能是汉字、字母、数字和下划线_及破折号-
func IsChsDash(value any) (ok bool) { func (this *IsStruct) ChsDash(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z0-9_-]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z0-9_-]+$`).MatchString(cast.ToString(value))
} }
// IsCntrl - 是否为控制字符 - (换行、缩进、空格) // Cntrl - 是否为控制字符 - (换行、缩进、空格)
func IsCntrl(value any) (ok bool) { func (this *IsStruct) Cntrl(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\x00-\x1F\x7F]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\x00-\x1F\x7F]+$`).MatchString(cast.ToString(value))
} }
// IsGraph - 是否为可见字符 - (除空格外的所有可打印字符) // Graph - 是否为可见字符 - (除空格外的所有可打印字符)
func IsGraph(value any) (ok bool) { func (this *IsStruct) Graph(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\x21-\x7E]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\x21-\x7E]+$`).MatchString(cast.ToString(value))
} }
// IsLower - 是否为小写字母 // Lower - 是否为小写字母
func IsLower(value any) (ok bool) { func (this *IsStruct) Lower(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[a-z]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[a-z]+$`).MatchString(cast.ToString(value))
} }
// IsUpper - 是否为大写字母 // Upper - 是否为大写字母
func IsUpper(value any) (ok bool) { func (this *IsStruct) Upper(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[A-Z]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[A-Z]+$`).MatchString(cast.ToString(value))
} }
// IsSpace - 是否为空白字符 - (空格、制表符、换页符等) // Space - 是否为空白字符 - (空格、制表符、换页符等)
func IsSpace(value any) (ok bool) { func (this *IsStruct) Space(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\s]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\s]+$`).MatchString(cast.ToString(value))
} }
// IsXdigit - 是否为十六进制字符 - 0-9、a-f、A-F // Xdigit - 是否为十六进制字符 - 0-9、a-f、A-F
func IsXdigit(value any) (ok bool) { func (this *IsStruct) Xdigit(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\da-fA-F]+$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[\da-fA-F]+$`).MatchString(cast.ToString(value))
} }
// IsActiveUrl - 是否为有效的域名或者IP // ActiveUrl - 是否为有效的域名或者IP
func IsActiveUrl(value any) (ok bool) { func (this *IsStruct) ActiveUrl(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^([a-z0-9-]+\.)+[a-z]{2,6}$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^([a-z0-9-]+\.)+[a-z]{2,6}$`).MatchString(cast.ToString(value))
} }
// IsIp - 是否为IP // Ip - 是否为IP
func IsIp(ip any) (ok bool) { func (this *IsStruct) Ip(ip any) (ok bool) {
if ip == nil { if ip == nil {
return false return false
} }
return regexp.MustCompile(`(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)`).MatchString(cast.ToString(ip)) return regexp.MustCompile(`(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)`).MatchString(cast.ToString(ip))
} }
// IsUrl - 是否为URL // Url - 是否为URL
func IsUrl(url any) (ok bool) { func (this *IsStruct) Url(url any) (ok bool) {
if url == nil { if url == nil {
return false return false
} }
return regexp.MustCompile(`^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+`).MatchString(cast.ToString(url)) return regexp.MustCompile(`^((https|http|ftp|rtsp|mms)?://)\S+`).MatchString(cast.ToString(url))
} }
// IsIdCard - 是否为有效的身份证号码 // IdCard - 是否为有效的身份证号码
func IsIdCard(value any) (ok bool) { func (this *IsStruct) IdCard(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)`).MatchString(cast.ToString(value)) return regexp.MustCompile(`(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)`).MatchString(cast.ToString(value))
} }
// IsMacAddr - 是否为有效的MAC地址 // MacAddr - 是否为有效的MAC地址
func IsMacAddr(value any) (ok bool) { func (this *IsStruct) MacAddr(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}$`).MatchString(cast.ToString(value))
} }
// IsZip - 是否为有效的邮政编码 // Zip - 是否为有效的邮政编码
func IsZip(value any) (ok bool) { func (this *IsStruct) Zip(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[1-9]\d{5}$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[1-9]\d{5}$`).MatchString(cast.ToString(value))
} }
// IsString - 是否为字符串 // String - 是否为字符串
func IsString(value any) (ok bool) { func (this *IsStruct) String(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return reflect.TypeOf(value).Kind() == reflect.String return reflect.TypeOf(value).Kind() == reflect.String
} }
// IsSlice - 是否为切片 // Slice - 是否为切片
func IsSlice(value any) (ok bool) { func (this *IsStruct) Slice(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return reflect.TypeOf(value).Kind() == reflect.Slice return reflect.TypeOf(value).Kind() == reflect.Slice
} }
// IsArray - 是否为数组 // Array - 是否为数组
func IsArray(value any) (ok bool) { func (this *IsStruct) Array(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return reflect.TypeOf(value).Kind() == reflect.Array return reflect.TypeOf(value).Kind() == reflect.Array
} }
// IsJsonString - 是否为json字符串 // JsonString - 是否为json字符串
func IsJsonString(value any) (ok bool) { func (this *IsStruct) JsonString(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return regexp.MustCompile(`^[\{\[].*[\}\]]$`).MatchString(cast.ToString(value)) return regexp.MustCompile(`^[{\[].*[}\]]$`).MatchString(cast.ToString(value))
} }
// IsMap - 是否为map // Map - 是否为map
func IsMap(value any) (ok bool) { func (this *IsStruct) Map(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return reflect.TypeOf(value).Kind() == reflect.Map return reflect.TypeOf(value).Kind() == reflect.Map
} }
// IsSliceSlice - 是否为二维切片 // SliceSlice - 是否为二维切片
func IsSliceSlice(value any) (ok bool) { func (this *IsStruct) SliceSlice(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }
return reflect.TypeOf(value).Kind() == reflect.Slice && reflect.TypeOf(value).Elem().Kind() == reflect.Slice return reflect.TypeOf(value).Kind() == reflect.Slice && reflect.TypeOf(value).Elem().Kind() == reflect.Slice
} }
// IsMapAny - 是否为[]map[string]any // MapAny - 是否为[]map[string]any
func IsMapAny(value any) (ok bool) { func (this *IsStruct) MapAny(value any) (ok bool) {
if value == nil { if value == nil {
return false return false
} }

View File

@@ -8,20 +8,25 @@ import (
"strings" "strings"
) )
// JsonEncode 编码 // Json - JSON 处理
func JsonEncode(data any) (result string) { var Json *JsonStruct
type JsonStruct struct{}
// Encode 编码
func (this *JsonStruct) Encode(data any) (result string) {
text, err := json.Marshal(data) text, err := json.Marshal(data)
return Ternary(err != nil, "", string(text)) return Ternary(err != nil, "", string(text))
} }
// JsonDecode 解码 // Decode 解码
func JsonDecode(data any) (result any) { func (this *JsonStruct) Decode(data any) (result any) {
err := json.Unmarshal([]byte(cast.ToString(data)), &result) err := json.Unmarshal([]byte(cast.ToString(data)), &result)
return Ternary(err != nil, nil, result) return Ternary(err != nil, nil, result)
} }
// JsonGet 获取json中的值 - 支持多级 // Get 获取json中的值 - 支持多级
func JsonGet(jsonString any, key any) (result any, err error) { func (this *JsonStruct) Get(jsonString any, key any) (result any, err error) {
if err := json.Unmarshal([]byte(cast.ToString(jsonString)), &result); err != nil { if err := json.Unmarshal([]byte(cast.ToString(jsonString)), &result); err != nil {
return nil, err return nil, err
@@ -44,8 +49,8 @@ func JsonGet(jsonString any, key any) (result any, err error) {
return result, nil return result, nil
} }
// JsonString map转json字符串 // String map转json字符串
func JsonString(data any) (result string) { func (this *JsonStruct) String(data any) (result string) {
item := cast.ToStringMap(data) item := cast.ToStringMap(data)

View File

@@ -22,9 +22,9 @@ func Lang(model ...LangModel) *LangModel {
} }
// 设置默认值 // 设置默认值
item.Lang = Ternary[string](!IsEmpty(item.Lang), item.Lang, "zh-cn") item.Lang = Ternary[string](!Is.Empty(item.Lang), item.Lang, "zh-cn")
item.Mode = Ternary[string](!IsEmpty(item.Mode), item.Mode, "json") item.Mode = Ternary[string](!Is.Empty(item.Mode), item.Mode, "json")
item.Directory = Ternary[string](!IsEmpty(item.Directory), item.Directory, "config/i18n/") item.Directory = Ternary[string](!Is.Empty(item.Directory), item.Directory, "config/i18n/")
return item return item
} }
@@ -41,21 +41,21 @@ func (this *LangModel) Value(key any, args ...any) (result any) {
text := cast.ToString(key) text := cast.ToString(key)
// 解析语言包 // 解析语言包
lang := cast.ToStringMap(JsonDecode(bytes.Text)) lang := cast.ToStringMap(Json.Decode(bytes.Text))
// 获取语言 // 获取语言
result = lang[text] result = lang[text]
// 如果没有找到语言通过javascript风格获取 // 如果没有找到语言通过javascript风格获取
if IsEmpty(result) { if Is.Empty(result) {
item, err := JsonGet(bytes.Text, text) item, err := Json.Get(bytes.Text, text)
if err == nil { if err == nil {
result = item result = item
} }
} }
// 如果没有找到语言,则返回原文 // 如果没有找到语言,则返回原文
if IsEmpty(result) { if Is.Empty(result) {
return fmt.Sprintf(text, args...) return fmt.Sprintf(text, args...)
} }

View File

@@ -5,6 +5,10 @@ import (
"strings" "strings"
) )
var Mime *MimeStruct
type MimeStruct struct{}
var MimeMap = map[string]string{ var MimeMap = map[string]string{
"js": "application/javascript", "js": "application/javascript",
"json": "application/json", "json": "application/json",
@@ -37,8 +41,8 @@ var MimeMap = map[string]string{
"md": "text/markdown", "md": "text/markdown",
} }
// MimeType 获取后缀对应的 mime // Type 获取后缀对应的 mime
func MimeType(suffix any) (mime string) { func (this *MimeStruct) Type(suffix any) (mime string) {
// 获取后缀 // 获取后缀
suffix = strings.ToLower(cast.ToString(suffix)) suffix = strings.ToLower(cast.ToString(suffix))
// 取出 . 后面的内容 // 取出 . 后面的内容

View File

@@ -7,7 +7,12 @@ import (
"time" "time"
) )
func NetTcping(host any, opts ...map[string]any) (ok bool, detail []map[string]any) { // Net - 网络
var Net *NetStruct
type NetStruct struct{}
func (this *NetStruct) Tcping(host any, opts ...map[string]any) (ok bool, detail []map[string]any) {
if len(opts) == 0 { if len(opts) == 0 {
opts = append(opts, map[string]any{ opts = append(opts, map[string]any{
@@ -16,8 +21,8 @@ func NetTcping(host any, opts ...map[string]any) (ok bool, detail []map[string]a
}) })
} }
opt := opts[0] opt := opts[0]
count := cast.ToInt(opt["count"]) count := cast.ToInt(opt["count"])
timeout := cast.ToDuration(opt["timeout"]) * time.Second timeout := cast.ToDuration(opt["timeout"]) * time.Second
// 读写锁 - 防止并发写入 // 读写锁 - 防止并发写入

View File

@@ -133,11 +133,11 @@ func typeof(args ...any) (typeof string, empty bool) {
} }
func CustomProcessApi(url string, api string) (result string) { func CustomProcessApi(url string, api string) (result string) {
if empty := IsEmpty(api); empty { if empty := Is.Empty(api); empty {
api = "api" api = "api"
} }
result = url result = url
if empty := IsEmpty(url); !empty { if empty := Is.Empty(url); !empty {
prefix := "//" prefix := "//"
if check := strings.HasPrefix(url, "https://"); check { if check := strings.HasPrefix(url, "https://"); check {
prefix = "https://" prefix = "https://"
@@ -145,7 +145,7 @@ func CustomProcessApi(url string, api string) (result string) {
prefix = "http://" prefix = "http://"
} }
// 正则匹配 http(s):// - 并去除 // 正则匹配 http(s):// - 并去除
url = regexp.MustCompile("^((https|http)?:\\/\\/)").ReplaceAllString(url, "") url = regexp.MustCompile("^((https|http)?://)").ReplaceAllString(url, "")
array := ArrayFilter(strings.Split(url, `/`)) array := ArrayFilter(strings.Split(url, `/`))
if len(array) == 1 { if len(array) == 1 {
result = prefix + array[0] + "/" + api + "/" result = prefix + array[0] + "/" + api + "/"

View File

@@ -36,9 +36,14 @@ func (this *wrLock) has(key string) (ok bool) {
return ok return ok
} }
// ParseParamsBefore - 解析参数 // Parse - 解析
var Parse *ParseStruct
type ParseStruct struct{}
// ParamsBefore - 解析参数
// 把 Content-Type = application/x-www-form-urlencoded 的参数解析成 object.deep.age = 10 的格式 // 把 Content-Type = application/x-www-form-urlencoded 的参数解析成 object.deep.age = 10 的格式
func ParseParamsBefore(params url.Values) (result map[string]any) { func (this *ParseStruct) ParamsBefore(params url.Values) (result map[string]any) {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wr := wrLock{ wr := wrLock{
@@ -116,9 +121,9 @@ func ParseParamsBefore(params url.Values) (result map[string]any) {
return wr.Data return wr.Data
} }
// ParseParams - 解析参数 // Params - 解析参数
// 把 Content-Type = application/x-www-form-urlencoded 的参数解析成 map[string]any // 把 Content-Type = application/x-www-form-urlencoded 的参数解析成 map[string]any
func ParseParams(params map[string]any) (result map[string]any) { func (this *ParseStruct) Params(params map[string]any) (result map[string]any) {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wr := wrLock{ wr := wrLock{
@@ -168,8 +173,8 @@ func ParseParams(params map[string]any) (result map[string]any) {
return wr.Data return wr.Data
} }
// ParseDomain - 解析域名 // Domain - 解析域名
func ParseDomain(value any) (domain string) { func (this *ParseStruct) Domain(value any) (domain string) {
URL, err := url.Parse(cast.ToString(value)) URL, err := url.Parse(cast.ToString(value))
if err != nil { if err != nil {
return "" return ""

View File

@@ -5,16 +5,21 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
// PasswordCreate - 创建密码 // Password - 密码
func PasswordCreate(password any) (result string) { var Password *PasswordStruct
type PasswordStruct struct{}
// Create - 创建密码
func (this *PasswordStruct) Create(password any) (result string) {
item, _ := bcrypt.GenerateFromPassword([]byte(password.(string)), bcrypt.MinCost) item, _ := bcrypt.GenerateFromPassword([]byte(password.(string)), bcrypt.MinCost)
return string(item) return string(item)
} }
// PasswordVerify - 验证密码 // Verify - 验证密码
func PasswordVerify(encode any, password any) (ok bool) { func (this *PasswordStruct) Verify(encode any, password any) (ok bool) {
if err := bcrypt.CompareHashAndPassword([]byte(cast.ToString(encode)), []byte(cast.ToString(password))); err != nil { if err := bcrypt.CompareHashAndPassword([]byte(cast.ToString(encode)), []byte(cast.ToString(password))); err != nil {
return false return false
} }

View File

@@ -48,7 +48,7 @@ func (this *RandStruct) String(length any, chars ...string) (result string) {
var charset string var charset string
if IsEmpty(chars) { if Is.Empty(chars) {
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
} else { } else {
charset = chars[0] charset = chars[0]
@@ -65,7 +65,7 @@ func (this *RandStruct) String(length any, chars ...string) (result string) {
// Int - 生成随机整数 // Int - 生成随机整数
func (this *RandStruct) Int(max any, min ...any) (result int) { func (this *RandStruct) Int(max any, min ...any) (result int) {
if IsEmpty(min) { if Is.Empty(min) {
min = []any{0} min = []any{0}
} }
if cast.ToInt(max) <= cast.ToInt(min[0]) { if cast.ToInt(max) <= cast.ToInt(min[0]) {

View File

@@ -5,8 +5,13 @@ import (
"reflect" "reflect"
) )
// StructSet - 动态给结构体赋值 // Struct - 操作结构体
func StructSet(obj any, key string, val any) { var Struct *StructStruct
type StructStruct struct{}
// Set - 动态给结构体赋值
func (this *StructStruct) Set(obj any, key string, val any) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 获取结构体的类型 // 获取结构体的类型
@@ -37,8 +42,8 @@ func StructSet(obj any, key string, val any) {
} }
} }
// StructGet - 动态获取结构体的值 // Get - 动态获取结构体的值
func StructGet(obj any, key string) (result any) { func (this *StructStruct) Get(obj any, key string) (result any) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 获取结构体的类型 // 获取结构体的类型
@@ -58,8 +63,8 @@ func StructGet(obj any, key string) (result any) {
return nil return nil
} }
// StructDel - 删除结构体的字段 // Del - 删除结构体的字段
func StructDel(obj any, key string) { func (this *StructStruct) Del(obj any, key string) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 获取结构体的类型 // 获取结构体的类型
@@ -78,8 +83,8 @@ func StructDel(obj any, key string) {
} }
} }
// StructHas - 判断结构体是否存在某个字段 // Has - 判断结构体是否存在某个字段
func StructHas(obj any, key string) (ok bool) { func (this *StructStruct) Has(obj any, key string) (ok bool) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 获取结构体的类型 // 获取结构体的类型
@@ -98,8 +103,8 @@ func StructHas(obj any, key string) (ok bool) {
return false return false
} }
// StructKeys - 获取结构体的字段 // Keys - 获取结构体的字段
func StructKeys(obj any) (slice []string) { func (this *StructStruct) Keys(obj any) (slice []string) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 获取结构体的类型 // 获取结构体的类型
@@ -118,8 +123,8 @@ func StructKeys(obj any) (slice []string) {
return keys return keys
} }
// StructValues - 获取结构体的值 // Values - 获取结构体的值
func StructValues(obj any) (slice []any) { func (this *StructStruct) Values(obj any) (slice []any) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 定义一个切片 // 定义一个切片
@@ -132,15 +137,15 @@ func StructValues(obj any) (slice []any) {
return keys return keys
} }
// StructLen - 获取结构体的长度 // Len - 获取结构体的长度
func StructLen(obj any) (length int) { func (this *StructStruct) Len(obj any) (length int) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
return value.NumField() return value.NumField()
} }
// StructMap - 将结构体转换为map // Map - 将结构体转换为map
func StructMap(obj any) (result map[string]any) { func (this *StructStruct) Map(obj any) (result map[string]any) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 获取结构体的类型 // 获取结构体的类型
@@ -159,8 +164,8 @@ func StructMap(obj any) (result map[string]any) {
return result return result
} }
// StructSlice - 将结构体转换为切片 // Slice - 将结构体转换为切片
func StructSlice(obj any) (slice []any) { func (this *StructStruct) Slice(obj any) (slice []any) {
// 获取结构体的值 // 获取结构体的值
value := reflect.ValueOf(obj).Elem() value := reflect.ValueOf(obj).Elem()
// 定义一个切片 // 定义一个切片

View File

@@ -5,14 +5,19 @@ import (
"regexp" "regexp"
) )
// UnityIds 参数归一 // Unity - 统一规范
func UnityIds(param ...any) (ids []any) { var Unity *UnityStruct
type UnityStruct struct{}
// Ids 参数归一化
func (this *UnityStruct) Ids(param ...any) (ids []any) {
fn := func(param any) (ids []any) { fn := func(param any) (ids []any) {
types := []string{"string", "int", "int64", "float", "float64"} types := []string{"string", "int", "int64", "float", "float64"}
if InArray(GetType(param), types) { if InArray(Get.Type(param), types) {
// 正则提取数字部分 // 正则提取数字部分
item := regexp.MustCompile(`\d+`).FindAllString(cast.ToString(param), -1) item := regexp.MustCompile(`\d+`).FindAllString(cast.ToString(param), -1)
for _, val := range item { for _, val := range item {
@@ -20,7 +25,7 @@ func UnityIds(param ...any) (ids []any) {
} }
} }
if GetType(param) == "slice" { if Get.Type(param) == "slice" {
item := cast.ToStringSlice(param) item := cast.ToStringSlice(param)
for _, val := range item { for _, val := range item {
ids = append(ids, cast.ToInt(val)) ids = append(ids, cast.ToInt(val))
@@ -36,8 +41,8 @@ func UnityIds(param ...any) (ids []any) {
return ArrayUnique(ArrayEmpty(ids)) return ArrayUnique(ArrayEmpty(ids))
} }
// UnityKeys 参数归一化 // Keys 参数归一化
func UnityKeys(param any, reg ...any) (keys []any) { func (this *UnityStruct) Keys(param any, reg ...any) (keys []any) {
// 正则表达式 // 正则表达式
var regex string var regex string
@@ -47,7 +52,7 @@ func UnityKeys(param any, reg ...any) (keys []any) {
regex = `[^,]+` regex = `[^,]+`
} }
if GetType(param) == "string" { if Get.Type(param) == "string" {
item := regexp.MustCompile(regex).FindAllString(cast.ToString(param), -1) item := regexp.MustCompile(regex).FindAllString(cast.ToString(param), -1)
@@ -55,7 +60,7 @@ func UnityKeys(param any, reg ...any) (keys []any) {
keys = append(keys, val) keys = append(keys, val)
} }
} }
if GetType(param) == "slice" { if Get.Type(param) == "slice" {
item := cast.ToStringSlice(param) item := cast.ToStringSlice(param)
for _, val := range item { for _, val := range item {
keys = append(keys, val) keys = append(keys, val)

View File

@@ -134,7 +134,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
// 判断 rules 是否包含 required // 判断 rules 是否包含 required
if !InArray("required", cast.ToStringSlice(rules)) { if !InArray("required", cast.ToStringSlice(rules)) {
// 判断 value 是否为空 // 判断 value 是否为空
if IsEmpty(value) { if Is.Empty(value) {
// 结束本次循环,进入下一次循环 // 结束本次循环,进入下一次循环
return nil return nil
} }
@@ -172,7 +172,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
switch val { switch val {
case "required": case "required":
if IsEmpty(value) { if Is.Empty(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " is not empty!" msg = name + " is not empty!"
@@ -180,7 +180,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "email": case "email":
if !IsEmail(value) { if !Is.Email(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <email> format!" msg = name + " format is incorrect! Required in <email> format!"
@@ -188,7 +188,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "number": case "number":
if !IsNumber(value) { if !Is.Number(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <number> format!" msg = name + " format is incorrect! Required in <number> format!"
@@ -196,7 +196,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "float": case "float":
if !IsFloat(value) { if !Is.Float(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <float> format!" msg = name + " format is incorrect! Required in <float> format!"
@@ -204,7 +204,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "bool": case "bool":
if !IsBool(value) { if !Is.Bool(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <bool> format!" msg = name + " format is incorrect! Required in <bool> format!"
@@ -212,7 +212,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "slice": case "slice":
if !IsSlice(value) { if !Is.Slice(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <array> format!" msg = name + " format is incorrect! Required in <array> format!"
@@ -220,7 +220,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "jsonStr": case "jsonStr":
if !IsJsonString(value) { if !Is.JsonString(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <json string> format!" msg = name + " format is incorrect! Required in <json string> format!"
@@ -228,7 +228,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "accepted": case "accepted":
if !IsAccepted(value) { if !Is.Accepted(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -236,7 +236,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "date": case "date":
if !IsDate(value) { if !Is.Date(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect! Required in <date> format!" msg = name + " format is incorrect! Required in <date> format!"
@@ -244,7 +244,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "alpha": case "alpha":
if !IsAlpha(value) { if !Is.Alpha(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -252,7 +252,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "alphaNum": case "alphaNum":
if !IsAlphaNum(value) { if !Is.AlphaNum(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -260,7 +260,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "alphaDash": case "alphaDash":
if !IsAlphaDash(value) { if !Is.AlphaDash(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -268,7 +268,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "chs": case "chs":
if !IsChs(value) { if !Is.Chs(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -276,7 +276,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "chsAlpha": case "chsAlpha":
if !IsChsAlpha(value) { if !Is.ChsAlpha(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -284,7 +284,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "chsAlphaNum": case "chsAlphaNum":
if !IsChsAlphaNum(value) { if !Is.ChsAlphaNum(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -292,7 +292,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "chsDash": case "chsDash":
if !IsChsDash(value) { if !Is.ChsDash(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -300,7 +300,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "cntrl": case "cntrl":
if !IsCntrl(value) { if !Is.Cntrl(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -308,7 +308,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "graph": case "graph":
if !IsGraph(value) { if !Is.Graph(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -316,7 +316,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "lower": case "lower":
if !IsLower(value) { if !Is.Lower(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -324,7 +324,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "upper": case "upper":
if !IsUpper(value) { if !Is.Upper(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -332,7 +332,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "space": case "space":
if !IsSpace(value) { if !Is.Space(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -340,7 +340,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "xdigit": case "xdigit":
if !IsXdigit(value) { if !Is.Xdigit(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -348,7 +348,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "activeUrl": case "activeUrl":
if !IsActiveUrl(value) { if !Is.ActiveUrl(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -356,7 +356,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "url": case "url":
if !IsUrl(value) { if !Is.Url(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -364,7 +364,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "ip": case "ip":
if !IsIp(value) { if !Is.Ip(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -372,7 +372,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "mobile": case "mobile":
if !IsMobile(value) { if !Is.Mobile(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -380,7 +380,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "idCard": case "idCard":
if !IsIdCard(value) { if !Is.IdCard(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -388,7 +388,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "MacAddr": case "MacAddr":
if !IsMacAddr(value) { if !Is.MacAddr(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"
@@ -396,7 +396,7 @@ func ValidateRules(name string, value any, rule string, message map[string]strin
return fmt.Errorf(msg) return fmt.Errorf(msg)
} }
case "zip": case "zip":
if !IsZip(value) { if !Is.Zip(value) {
msg := message[name+"."+val] msg := message[name+"."+val]
if msg == "" { if msg == "" {
msg = name + " format is incorrect!" msg = name + " format is incorrect!"

View File

@@ -8,20 +8,25 @@ import (
"strings" "strings"
) )
// VersionGo - 获取当前go版本 // Version - 版本
func VersionGo() (result string) { var Version *VersionStruct
type VersionStruct struct{}
// Go - 获取当前go版本号
func (this *VersionStruct) Go() (result string) {
return strings.Replace(runtime.Version(), "go", "", -1) return strings.Replace(runtime.Version(), "go", "", -1)
} }
// VersionCompare - 版本号比对 // Compare - 版本号比对
/** /**
* @param v1 string - 小版本号 * @param v1 string - 小版本号
* @param v2 string - 大版本号 * @param v2 string - 大版本号
* @return int - 0: 相等1: v1 < v2-1: v1 > v2 * @return int - 0: 相等1: v1 < v2-1: v1 > v2
* @example * @example
* utils.VersionCompare("1.2.0", "1.0.0") // 1 * utils.Version.Compare("1.2.0", "1.0.0") // 1
*/ */
func VersionCompare(v1, v2 any) (result int) { func (this *VersionStruct) Compare(v1, v2 any) (result int) {
rule := regexp.MustCompile(`\d+`) rule := regexp.MustCompile(`\d+`)
v1Arr := rule.FindAllString(cast.ToString(v1), -1) v1Arr := rule.FindAllString(cast.ToString(v1), -1)

View File

@@ -56,25 +56,25 @@ func (this *ViperModel) Read() (result ViperResponse) {
item := viper.New() item := viper.New()
if !IsEmpty(this.Path) { if !Is.Empty(this.Path) {
item.AddConfigPath(this.Path) item.AddConfigPath(this.Path)
} }
if !IsEmpty(this.Mode) { if !Is.Empty(this.Mode) {
item.SetConfigType(this.Mode) item.SetConfigType(this.Mode)
} }
if !IsEmpty(this.Name) { if !Is.Empty(this.Name) {
item.SetConfigName(this.Name) item.SetConfigName(this.Name)
} }
result.Viper = item result.Viper = item
result.Error = item.ReadInConfig() result.Error = item.ReadInConfig()
result.Result = cast.ToStringMap(item.AllSettings()) result.Result = cast.ToStringMap(item.AllSettings())
if result.Error != nil { if result.Error != nil {
// 如果错误中包含文件不存在,则创建文件 // 如果错误中包含文件不存在,则创建文件
if !os.IsNotExist(result.Error) && !IsEmpty(this.Content) { if !os.IsNotExist(result.Error) && !Is.Empty(this.Content) {
path := this.Path + "/" + this.Name + "." + this.Mode path := this.Path + "/" + this.Name + "." + this.Mode
@@ -113,9 +113,7 @@ func (this *ViperResponse) Get(key string, def ...any) (result any) {
} }
result = this.Viper.Get(key) result = this.Viper.Get(key)
result = Ternary(!IsEmpty(result), result, item) result = Ternary(!Is.Empty(result), result, item)
// result = Ternary(this.Result[key] != nil, this.Result[key], this.Viper.Get(key))
return return
} }