You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
package util
import ( "encoding/hex" "fmt" "regexp" "sort" "strings"
uuid "github.com/satori/go.uuid" )
var GUUID *UUIDFactory = new(UUIDFactory) var EmptyUUID = "00000000-0000-0000-0000-000000000000"
type UUIDFactory struct { uid uuid.UUID }
func (nu *UUIDFactory) NewV1() *UUIDFactory { uid := uuid.NewV1() nu.uid = uid return nu }
func (nu *UUIDFactory) Sort() []byte { return UUIDToBytes(nu.String()) }
func (nu *UUIDFactory) String() string { return Sort(nu.uid.String()) //strings.Replace(Sort(nu.uid.String()), "-", "", -1)
}
func BytesToUUID(b []byte) string { hs := hex.EncodeToString(b) return hs[0:8] + "-" + hs[8:12] + "-" + hs[12:16] + "-" + hs[16:20] + "-" + hs[20:32] }
func UUIDToBytes(s string) []byte { if s == "" { fmt.Println("空uid") return []byte("00000000-0000-0000-0000-000000000000") }
if !IsUUID(s) { fmt.Errorf("非法UUID:%s", s) } if strings.Contains(s, "-") { s = strings.Replace(s, "-", "", -1) }
b, err := hex.DecodeString(s)
if err != nil { //CheckError(err)
}
return b }
//校验是否为合法的UUID,合法UUID格式为16进制字符和“-”组成,类似如下的格式:
//(1)11e90a62-f2fa-07ce-9e60-0242ac110007
//(2)11E90A62-F2fa-07ce-9e60-0242ac11000A
//(3)11e90a62f2fa07ce9e600242ac110007
//(4)11E90A62F2fa07ce9e600242ac11000A
//以下格式字符串为非法UUID:
//(1)11e90a62-f2fa-07ce-9e60-0242ac11000x(包含16进制字符之外的字符“x”,非法)
//(2)11e90a62-f2fa-07ce-9e60-0242ac11000X(包含16进制字符之外的字符“X”,非法)
//(3)11e90a62f2fa07ce9e600242ac11000x(包含16进制字符之外的字符“x”,非法)
//(4)11e90a62f2fa07ce9e600242ac11000X(包含16进制字符之外的字符“X”,非法)
//(5)11e90a62f2fa07ce9e600242ac11000(不包含“-”27位,非法)
//(6)11e90a62-f2fa-07ce-9e60-0242ac11000(31位,非法)
//(7)11e90a62-f2fa-07ce-9e600242ac110007(缺少“-”的31位字符串,非法)
func IsUUID(s string) bool { const pattern = `[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}|[0-9a-fA-F]{32}` if b, err := regexp.MatchString(pattern, s); b && err == nil { return true } return false }
func Sort(uid string) string { us := strings.Split(uid, "-")
var res []string
res = append(res, us[1]+us[2]) res = append(res, string([]rune(us[0])[4:8])) res = append(res, string([]rune(us[0])[:4])) res = append(res, us[3]) res = append(res, us[4])
return strings.Join(res, "-") }
func IsEmptyUUID(uid string) bool { return len(uid) == 0 || len(strings.TrimSpace(uid)) == 0 || uid == "00000000-0000-0000-0000-000000000000" || uid == "00000000000000000000000000000000" || uid == "30780000-0000-0000-0000-000000000000" }
func IsValidUUID(uid string) bool { return !IsEmptyUUID(uid) && IsUUID(uid) }
// 数组切片去重
func SliceRemoveDuplicates(slice []string) []string { sort.Strings(slice) i := 0 var j int for { if i >= len(slice)-1 { break }
for j = i + 1; j < len(slice) && slice[i] == slice[j]; j++ { } slice = append(slice[:i+1], slice[j:]...) i++ } return slice }
|