-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
490 lines (358 loc) · 9.64 KB
/
util.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package mylib
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha256"
b64 "encoding/base64"
"encoding/hex"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"regexp"
"strings"
"time"
"github.com/xdg-go/pbkdf2"
)
type Block struct {
Try func()
Catch func(Exception)
Finally func()
}
type Exception interface{}
func Throw(up Exception) {
panic(up)
}
func (tcf Block) Do() {
if tcf.Finally != nil {
defer tcf.Finally()
}
if tcf.Catch != nil {
defer func() {
if r := recover(); r != nil {
tcf.Catch(r)
}
}()
}
tcf.Try()
}
func (l *Utils) GetFormatTime(layout string) string {
// Standard GO Constant Format :
// ANSIC = "Mon Jan _2 15:04:05 2006"
// UnixDate = "Mon Jan _2 15:04:05 MST 2006"
// RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
// RFC822 = "02 Jan 06 15:04 MST"
// RFC822Z = "02 Jan 06 15:04 -0700"
// RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
// RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
// RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700"
// RFC3339 = "2006-01-02T15:04:05Z07:00"
// RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
// Kitchen = "3:04PM"
// // Handy time stamps.
// Stamp = "Jan _2 15:04:05"
// StampMilli = "Jan _2 15:04:05.000"
// StampMicro = "Jan _2 15:04:05.000000"
// StampNano = "Jan _2 15:04:05.000000000"
// Using Manual Format :
// 1. date yyyy-mm-dd = 2006-01-02
// 2. time hhhh:ii:ss = 15:04:05
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
t := time.Now()
f := t.In(loc).Format(layout)
return f
}
func (l *Utils) GetUniqId() string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
t := time.Now()
var formatId = t.In(loc).Format("20060102150405.000000")
uniqId := strings.Replace(formatId, ".", "", -1)
return uniqId
}
func (l *Utils) GetLogId() string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
t := time.Now()
var formatId = t.In(loc).Format("20060102150405")
logId := strings.Replace(formatId, ".", "", -1)
return logId
}
func (l *Utils) GetDate(dateFormat string) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
t := time.Now()
var now = t.In(loc).Format(dateFormat)
return now
}
func (l *Utils) GetDateTimeAdd(init string, add int, dateFormat string) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
t := time.Now()
var now string
if init == "hour" {
now = t.Add(time.Hour * time.Duration(add)).In(loc).Format(dateFormat)
} else if init == "minute" {
now = t.Add(time.Minute * time.Duration(add)).In(loc).Format(dateFormat)
} else if init == "second" {
now = t.Add(time.Second * time.Duration(add)).In(loc).Format(dateFormat)
} else if init == "day" {
now = t.AddDate(0, 0, add).In(loc).Format(dateFormat)
} else if init == "month" {
now = t.AddDate(0, 1, 0).In(loc).Format(dateFormat)
} else if init == "year" {
now = t.AddDate(add, 0, 0).In(loc).Format(dateFormat)
}
return now
}
func (l *Utils) GetYesterday(day time.Duration) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
var format = "2006-01-02"
now := time.Now()
var curDate = now.In(loc).Format(format)
t, _ := time.Parse(format, curDate)
yesterday := 24 * day
nano := t.Add(-yesterday * time.Hour).UnixNano()
return time.Unix(0, nano).Format(format)
}
func (l *Utils) GetTomorrow(day time.Duration) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
var format = "2006-01-02"
now := time.Now()
var curDate = now.In(loc).Format(format)
t, _ := time.Parse(format, curDate)
tomorrow := 24 * day
nano := t.In(loc).Add(tomorrow * time.Hour).UnixNano()
return time.Unix(0, nano).Format(format)
}
func (l *Utils) GetYesterdayWithFormat(day time.Duration, formatDate string) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
//var format = "2006-01-02"
now := time.Now()
var curDate = now.In(loc).Format(formatDate)
t, _ := time.Parse(formatDate, curDate)
yesterday := 24 * day
nano := t.Add(-yesterday * time.Hour).UnixNano()
return time.Unix(0, nano).Format(formatDate)
}
func (l *Utils) GetTomorrowWithFormat(day time.Duration, formatDate string) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
//var format = "2006-01-02"
now := time.Now()
var curDate = now.In(loc).Format(formatDate)
t, _ := time.Parse(formatDate, curDate)
tomorrow := 24 * day
nano := t.In(loc).Add(tomorrow * time.Hour).UnixNano()
return time.Unix(0, nano).Format(formatDate)
}
func (l *Utils) GetDateAdd(format string, day int, month int, year int) string {
//set timezone,
loc, _ := time.LoadLocation(l.TimeZone)
t := time.Now()
now := t.In(loc).AddDate(year, month, day).Format(format)
return now
}
func BytesToString(data []byte) string {
return string(data[:])
}
func InlinePrintingXML(xmlString string) string {
var unformatXMLRegEx = regexp.MustCompile(`>\s+<`)
unformatBetweenTags := unformatXMLRegEx.ReplaceAllString(xmlString, "><") // remove whitespace between XML tags
return strings.TrimSpace(unformatBetweenTags) // remove whitespace before and after XML
}
func Concat(args ...string) string {
var b bytes.Buffer
for _, arg := range args {
b.WriteString(arg)
}
return b.String()
}
// WriteOnFile function
// Args:
// 1. data = @string
// 2. file = @string
// 3. append = @boolean
// 4. mod = @string
func WriteOnFile(data string, file string, append bool, mode os.FileMode) {
var (
f *os.File
)
if append {
f, _ = os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, mode)
} else {
f, _ = os.OpenFile(file, os.O_CREATE|os.O_WRONLY, mode)
}
if _, err := f.WriteString(data); err != nil {
fmt.Println(err)
}
defer f.Close()
}
func ReadOnFile(file string) string {
content, _ := os.ReadFile(file)
return string(content)
}
func ReduceWords(words string, start int, length int) string {
runes := []rune(words)
inputFmt := string(runes[start:length])
return inputFmt
}
func Base64EncStd(data string) string {
return b64.StdEncoding.EncodeToString([]byte(data))
}
func Base64DecStd(data string) string {
sDec, _ := b64.StdEncoding.DecodeString(data)
return string(sDec)
}
func Base64EncUrl(data string) string {
return b64.URLEncoding.EncodeToString([]byte(data))
}
func Base64DecUrl(data string) string {
sDec, _ := b64.URLEncoding.DecodeString(data)
return string(sDec)
}
func RNG(min int, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max-min+1) + min
}
func CounterZeroNumber(length int) string {
var wordNumbers string
for w := 0; w < length; w++ {
wordNumbers += "0"
}
return wordNumbers
}
func RemoveTabAndEnter(str string) string {
space := regexp.MustCompile(`\s+`)
r := space.ReplaceAllString(str, " ")
return r
}
func GetMD5(s string) string {
// Secret key
data := md5.Sum([]byte(s))
secretKey := hex.EncodeToString(data[:])
return secretKey
}
func ReadASingleValueInFile(filename string, keyword string) string {
var path []string
if _, err := os.Stat(filename); err == nil {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, keyword) {
path = strings.Split(line, "=")
break
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
return path[1]
}
func ContainsInt(i []int, e int) bool {
for _, a := range i {
if a == e {
return true
}
}
return false
}
func ContainsStr(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func ReadGzFile(filename string) ([]byte, error) {
fi, err := os.Open(filename)
if err != nil {
return nil, err
}
defer fi.Close()
fz, err := gzip.NewReader(fi)
if err != nil {
return nil, err
}
defer fz.Close()
s := bufio.NewScanner(fz)
return s.Bytes(), nil
}
func Copy(srcFolder string, destFolder string) bool {
cpCmd := exec.Command("cp", "-pa", srcFolder, destFolder)
err := cpCmd.Run()
if err == nil {
return true
} else {
return false
}
}
func Shellout(command string) (string, string, error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command("bash", "-c", command)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), stderr.String(), err
}
func Aes256Encode(plaintext string, key []byte, iv string, blockSize int) string {
bIV := []byte(iv)
bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext))
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
ciphertext := make([]byte, len(bPlaintext))
mode := cipher.NewCBCEncrypter(block, bIV)
mode.CryptBlocks(ciphertext, bPlaintext)
return hex.EncodeToString(ciphertext)
}
func Aes256Decode(cipherText string, encKey []byte, iv string) (string, error) {
var (
err error
cipherTextDecoded []byte
block cipher.Block
)
bIV := []byte(iv)
cipherTextDecoded, err = hex.DecodeString(cipherText)
if err != nil {
return "", err
}
block, err = aes.NewCipher(encKey)
if err != nil {
return "", err
}
mode := cipher.NewCBCDecrypter(block, bIV)
mode.CryptBlocks([]byte(cipherTextDecoded), []byte(cipherTextDecoded))
return string(cipherTextDecoded), nil
}
func DeriveKey(passphrase string, salt []byte) []byte {
// http://www.ietf.org/rfc/rfc2898.txt
if salt == nil {
salt = make([]byte, 8)
// rand.Read(salt)
}
return pbkdf2.Key([]byte(passphrase), salt, 1000, 32, sha256.New)
}
func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte {
padding := (blockSize - len(ciphertext)%blockSize)
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}