-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
123 lines (108 loc) · 2.31 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package util
import (
"context"
"crypto/md5"
"crypto/sha1"
"encoding/hex"
"fmt"
"hash"
"io"
"time"
"github.com/easonchen147/foundation/constant"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
gonanoid "github.com/matoous/go-nanoid/v2"
)
func MD5(str []byte) string {
h := md5.New()
h.Write(str)
return hex.EncodeToString(h.Sum(nil))
}
func Sha1(str []byte) string {
h := sha1.New()
h.Write(str)
return hex.EncodeToString(h.Sum(nil))
}
// FileHash 计算文件hash
func FileHash(reader io.Reader, tp string) string {
var result []byte
var h hash.Hash
if tp == "md5" {
h = md5.New()
} else {
h = sha1.New()
}
if _, err := io.Copy(h, reader); err != nil {
return ""
}
return fmt.Sprintf("%x", h.Sum(result))
}
// GetUuid 生成uuid
func GetUuid() string {
var u uuid.UUID
var err error
for i := 0; i < 3; i++ {
u, err = uuid.NewUUID()
if err == nil {
return u.String()
}
}
return ""
}
// GetUuidV4 生成uuid v4
func GetUuidV4() string {
var u uuid.UUID
var err error
for i := 0; i < 3; i++ {
u, err = uuid.NewRandom()
if err == nil {
return u.String()
}
}
return ""
}
// ParseDate 转时间格式 yyyy-MM-dd
func ParseDate(date string) time.Time {
result, err := time.ParseInLocation(constant.DateFormat, date, time.Local)
if err != nil {
return time.Time{}
}
return result
}
// ParseDateTime 转时间格式 yyyy-MM-dd HH:mm:ss
func ParseDateTime(dateTime string) time.Time {
result, err := time.ParseInLocation(constant.DateTimeFormat, dateTime, time.Local)
if err != nil {
return time.Time{}
}
return result
}
// FormatDate 转时间格式 yyyy-MM-dd
func FormatDate(date time.Time) string {
return date.Format(constant.DateFormat)
}
// FormatDateTime 转时间格式 yyyy-MM-dd HH:mm:ss
func FormatDateTime(dateTime time.Time) string {
return dateTime.Format(constant.DateTimeFormat)
}
// CopyGinCtx 复制ginCtx
func CopyGinCtx(ctx *gin.Context) context.Context {
return ctx.Copy()
}
// CopyCtx 拷贝Context,判断如果是ginCtx则需要拷贝
func CopyCtx(ctx context.Context) context.Context {
switch ctx.(type) {
case *gin.Context:
return ctx.(*gin.Context).Copy()
default:
return ctx
}
}
// GetNanoId 获取32位的nanoId
func GetNanoId() string {
id, err := gonanoid.Generate(constant.NanoIdAlphbet, 32)
if err != nil {
return ""
}
return id
}