This repository has been archived by the owner on Dec 8, 2020. It is now read-only.
forked from shenghui0779/yiigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
238 lines (179 loc) · 5.37 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package yiigo
import (
"bytes"
"encoding/xml"
"errors"
"math"
"net"
"strings"
"sync"
"time"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zhcn "github.com/go-playground/validator/v10/translations/zh"
"github.com/hashicorp/go-version"
"go.uber.org/zap"
)
// AsDefault alias for "default"
const AsDefault = "default"
// X is a convenient alias for a map[string]interface{}.
type X map[string]interface{}
// CDATA XML CDATA section which is defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup.
type CDATA string
// MarshalXML encodes the receiver as zero or more XML elements.
func (c CDATA) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return e.EncodeElement(struct {
string `xml:",cdata"`
}{string(c)}, start)
}
// Date format a local time/date and
// returns a string formatted according to the given format string using the given timestamp of int64.
// The default layout is: 2006-01-02 15:04:05.
func Date(timestamp int64, layout ...string) string {
l := "2006-01-02 15:04:05"
if len(layout) > 0 {
l = layout[0]
}
date := time.Unix(timestamp, 0).Format(l)
return date
}
// StrToTime Parse English textual datetime description into a Unix timestamp.
// The default layout is: 2006-01-02 15:04:05.
func StrToTime(datetime string, layout ...string) int64 {
l := "2006-01-02 15:04:05"
if len(layout) > 0 {
l = layout[0]
}
t, err := time.ParseInLocation(l, datetime, time.Local)
// mismatch layout
if err != nil {
logger.Error("parse layout mismatch", zap.Error(err))
return 0
}
return t.Unix()
}
// WeekAround returns the date of monday and sunday for current week
func WeekAround() (monday, sunday string) {
now := time.Now()
offset := int(time.Monday - now.Weekday())
if offset > 0 {
offset = -6
}
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
monday = today.AddDate(0, 0, offset).Format("20060102")
offset = int(time.Sunday - now.Weekday())
if offset < 0 {
offset += 7
}
sunday = today.AddDate(0, 0, offset).Format("20060102")
return
}
// IP2Long converts a string containing an (IPv4) Internet Protocol dotted address into a long integer.
func IP2Long(ip string) uint32 {
ipv4 := net.ParseIP(ip).To4()
if ipv4 == nil {
return 0
}
return uint32(ipv4[0])<<24 | uint32(ipv4[1])<<16 | uint32(ipv4[2])<<8 | uint32(ipv4[3])
}
// Long2IP converts an long integer address into a string in (IPv4) Internet standard dotted format.
func Long2IP(ip uint32) string {
if ip > math.MaxUint32 {
return ""
}
return net.IPv4(byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip)).String()
}
// BufferPool type of buffer pool
type BufferPool struct {
pool sync.Pool
}
// Get return a buffer
func (b *BufferPool) Get() *bytes.Buffer {
buf := b.pool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
// Put put a buffer to pool
func (b *BufferPool) Put(buf *bytes.Buffer) {
if buf == nil {
return
}
b.pool.Put(buf)
}
// NewBufferPool returns a new buffer pool
func NewBufferPool(cap int64) *BufferPool {
return &BufferPool{pool: sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, cap))
},
}}
}
// BufPool buffer pool
var BufPool = NewBufferPool(4 << 10) // 4KB
// GinValidator validator for gin
type GinValidator struct {
validator *validator.Validate
translator ut.Translator
}
// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
func (v *GinValidator) ValidateStruct(obj interface{}) error {
if err := v.validator.Struct(obj); err != nil {
e, ok := err.(validator.ValidationErrors)
if !ok {
return e
}
errM := e.Translate(v.translator)
msgs := make([]string, 0, len(errM))
for _, v := range errM {
msgs = append(msgs, v)
}
return errors.New(strings.Join(msgs, ";"))
}
return nil
}
// Engine returns the underlying validator engine which powers the default
// Validator instance. This is useful if you want to register custom validations
// or struct level validations. See validator GoDoc for more info -
// https://godoc.org/gopkg.in/go-playground/validator.v10
func (v *GinValidator) Engine() interface{} {
return v.validator
}
// NewGinValidator returns a validator for gin
func NewGinValidator() *GinValidator {
zhCn := zh.New()
uniTrans := ut.New(zhCn)
validate := validator.New()
validate.SetTagName("valid")
translator, _ := uniTrans.GetTranslator("zh")
zhcn.RegisterDefaultTranslations(validate, translator)
return &GinValidator{
validator: validate,
translator: translator,
}
}
// VersionCompare compares semantic versions range, support: >, >=, =, !=, <, <=, | (or), & (and)
// eg: 1.0.0, =1.0.0, >2.0.0, >=1.0.0&<2.0.0, <2.0.0|>3.0.0, !=4.0.4
func VersionCompare(rangeVer, curVer string) bool {
if rangeVer == "" || curVer == "" {
return true
}
semVer, err := version.NewVersion(curVer)
// invalid semantic version
if err != nil {
return true
}
orVers := strings.Split(rangeVer, "|")
for _, ver := range orVers {
andVers := strings.Split(ver, "&")
constraints, err := version.NewConstraint(strings.Join(andVers, ","))
if err != nil {
logger.Error("version compared error", zap.Error(err), zap.String("range_version", rangeVer), zap.String("cur_version", curVer))
return true
}
if constraints.Check(semVer) {
return true
}
}
return false
}