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.

353 lines
8.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package CommonUtil
import (
"bytes"
"crypto/md5"
"encoding/binary"
"encoding/hex"
"fmt"
uuid "github.com/satori/go.uuid"
"math/rand"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
/**
功能获取UUID
作者:黄海
时间2020-02-03
*/
func GetUUID() string {
u2 := strings.ToUpper(uuid.NewV4().String())
return u2
}
/**
功能从一个数据库的查询返回结果中获取指定字段的IDS
作者:黄海
时间2020-02-14
*/
func SelectIdsFromMapInterface(list []map[string]interface{}, key string) []string {
var ids []string
for i := 0; i < len(list); i++ {
switch list[i][key].(type) {
case string:
ids = append(ids, list[i][key].(string))
break
case int64:
ids = append(ids, strconv.FormatInt(list[i][key].(int64), 10))
}
}
return ids
}
/**
功能:将一个数据库查询返回结果中的某一列,形成字典
作者:黄海
时间2020-02-14
*/
func PutSelectResultToMapByField(list []map[string]interface{}, field string) map[string]interface{} {
_dict := make(map[string]interface{})
for i, _ := range list {
record := list[i]
switch record[field].(type) {
case int64:
_dict[strconv.FormatInt(record[field].(int64), 10)] = 1
default:
_dict[record[field].(string)] = 1
}
}
return _dict
}
/**
功能:通过字典获取字符串数组
作者:黄海
时间2020-02-14
*/
func GetArrayByMap(_dict map[string]interface{}) []string {
Ids := make([]string, 0, len(_dict))
for k := range _dict {
Ids = append(Ids, k) //
}
return Ids
}
/**
功能:将数据库返回的查询结果映射成字典,用于扩展字段
作者:黄海
时间2020-02-14
*/
func ConvertMapInterfaceToMapByField(list []map[string]interface{}, key string, value string) map[string]string {
_map := make(map[string]string)
for i, _ := range list {
var areaTypeId string
switch list[i][key].(type) {
case int64:
areaTypeId = strconv.FormatInt(list[i][key].(int64), 10)
default:
areaTypeId = list[i][key].(string)
}
switch list[i][value].(type) {
case int64:
_map[areaTypeId] = strconv.FormatInt(list[i][value].(int64), 10)
default:
_map[areaTypeId] = list[i][value].(string)
}
}
return _map
}
/**
功能:扩展数据库查询结果集
作者:黄海
时间2020-02-14
*/
func ExtendList(list *[]map[string]interface{}, _map map[string]string, key string, value string) {
for i, _ := range *list {
sourceRecord := (*list)[i]
var a string
switch sourceRecord[key].(type) {
case int64:
a = strconv.FormatInt(sourceRecord[key].(int64), 10)
default:
a = sourceRecord[key].(string)
}
sourceRecord[value] = _map[a]
}
}
/**
功能:判断是不是合法的日期格式
作者:黄海
时间2020-03-23
*/
func IsDate(date string) bool{
_, err := time.Parse("2006-01-02 15:04:05", date)
if err!=nil{
return false
}else {
return true
}
}
/**
功能:删除字符串多余的空格
作者:黄海
时间2020-01-20
*/
func DeleteExtraSpace(s string) string {
//删除字符串中的多余空格,有多个空格时,仅保留一个空格
s1 := strings.Replace(s, " ", " ", -1) //替换tab为空格
regstr := "\\s{2,}" //两个及两个以上空格的正则表达式
reg, _ := regexp.Compile(regstr) //编译正则表达式
s2 := make([]byte, len(s1)) //定义字符数组切片
copy(s2, s1) //将字符串复制到切片
spcIndex := reg.FindStringIndex(string(s2)) //在字符串中搜索
for len(spcIndex) > 0 { //找到适配项
s2 = append(s2[:spcIndex[0]+1], s2[spcIndex[1]:]...) //删除多余空格
spcIndex = reg.FindStringIndex(string(s2)) //继续在字符串中搜索
}
return string(s2)
}
// Capitalize 字符首字母大写
func Capitalize(str string) string {
var upperStr string
vv := []rune(str) // 后文有介绍
for i := 0; i < len(vv); i++ {
if i == 0 {
if vv[i] >= 97 && vv[i] <= 122 { // 后文有介绍
vv[i] -= 32 // string的码表相差32位
upperStr += string(vv[i])
} else {
fmt.Println("Not begins with lowercase letter,")
return str
}
} else {
upperStr += string(vv[i])
}
}
return upperStr
}
/**
功能:获取蛇形命名的字符串
作者:黄海
时间2020-01-22
*/
func GetSnakeCaseStr(str string) string {
array := strings.Split(str, "_")
var result string
for i := 0; i < len(array); i++ {
result = result + strings.ToUpper(array[i][0:1]) + array[i][1:]
}
return result
}
const (
// 可自定义盐值
TokenSalt = "DsideaL4r5t6y7u"
)
func MD5(data []byte) string {
_md5 := md5.New()
_md5.Write(data)
return hex.EncodeToString(_md5.Sum([]byte("")))
}
//isSymbol表示有无符号
func BytesToInt(b []byte, isSymbol bool) (int, error) {
if isSymbol {
return BytesToIntS(b)
}
return bytesToIntU(b)
}
//字节数(大端)组转成int(无符号的)
func bytesToIntU(b []byte) (int, error) {
if len(b) == 3 {
b = append([]byte{0}, b...)
}
bytesBuffer := bytes.NewBuffer(b)
switch len(b) {
case 1:
var tmp uint8
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 2:
var tmp uint16
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 4:
var tmp uint32
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
default:
return 0, fmt.Errorf("%s", "BytesToInt bytes lenth is invaild!")
}
}
//字节数(大端)组转成int(有符号)
func BytesToIntS(b []byte) (int, error) {
if len(b) == 3 {
b = append([]byte{0}, b...)
}
bytesBuffer := bytes.NewBuffer(b)
switch len(b) {
case 1:
var tmp int8
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 2:
var tmp int16
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 4:
var tmp int32
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
default:
return 0, fmt.Errorf("%s", "BytesToInt bytes lenth is invaild!")
}
}
//整形转换成字节
func IntToBytes(n int, b byte) ([]byte, error) {
switch b {
case 1:
tmp := int8(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(), nil
case 2:
tmp := int16(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(), nil
case 3, 4:
tmp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(), nil
}
return nil, fmt.Errorf("IntToBytes b param is invaild")
}
/**
功能:生成一个随机盐
作者: 黄海
时间2020-02-18
*/
func GetRandomSalt() string {
return GetRandomString(8)
}
//生成随机字符串
func GetRandomString(l int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
var result []byte
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}
/**
功能将int数据类型转为int64
作者:黄海
时间2020-02-18
*/
func ConvertIntToInt64(i int) int64 {
s := strconv.Itoa(i)
s64, _ := strconv.ParseInt(s, 10, 64)
return s64
}
/**
功能:获取当前的时间戳,精确度纳秒
作者:黄海
时间2020-02-18
*/
func GetCurrentTimestamp() int64 {
return time.Now().UnixNano()
}
/**
功能:获取当前的时间字符串
作者:黄海
时间2020-02-21
*/
func GetCurrentTime() string {
timeStr := time.Now().Format("2006-01-02 15:04:05")
//当前时间的字符串2006-01-02 15:04:05据说是golang的诞生时间固定写法
return timeStr
}
/*
获取程序运行路径
*/
func GetCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
fmt.Println(err)
}
return strings.Replace(dir, "\\", "/", -1)
}
// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}