/
helper-str.go
783 lines (633 loc) · 19.7 KB
/
helper-str.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
package helper
/*
* Copyright 2020-2023 Aldelo, LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
"github.com/aldelo/common/ascii"
"html"
"regexp"
"strings"
)
// LenTrim returns length of space trimmed string s
func LenTrim(s string) int {
return len(strings.TrimSpace(s))
}
// NextFixedLength calculates the next fixed length total block size,
// for example, if block size is 16, then the total size should be 16, 32, 48 and so on based on data length
func NextFixedLength(data string, blockSize int) int {
blocks := (len(data) / blockSize) + 1
blocks = blocks * blockSize
return blocks
}
// Left returns the left side of string indicated by variable l (size of substring)
func Left(s string, l int) string {
if len(s) <= l {
return s
}
if l <= 0 {
return s
}
return s[0:l]
}
// Right returns the right side of string indicated by variable l (size of substring)
func Right(s string, l int) string {
if len(s) <= l {
return s
}
if l <= 0 {
return s
}
return s[len(s)-l:]
}
// Mid returns the middle of string indicated by variable start and l positions (size of substring)
func Mid(s string, start int, l int) string {
if len(s) <= l {
return s
}
if l <= 0 {
return s
}
if start > len(s)-1 {
return s
}
if (len(s) - start) < l {
return s
}
return s[start : l+start]
}
// Reverse a string
func Reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
// Replace will replace old char with new char and return the replaced string
func Replace(s string, oldChar string, newChar string) string {
return strings.Replace(s, oldChar, newChar, -1)
}
// Trim gets the left and right space trimmed input string s
func Trim(s string) string {
return strings.TrimSpace(s)
}
// RightTrimLF will remove linefeed (return char) from the right most char and return result string
func RightTrimLF(s string) string {
if LenTrim(s) > 0 {
if Right(s, 2) == "\r\n" {
return Left(s, len(s)-2)
}
if Right(s, 1) == "\n" {
return Left(s, len(s)-1)
}
}
return s
}
// Padding will pad the data with specified char either to the left or right
func Padding(data string, totalSize int, padRight bool, padChar string) string {
var result string
result = data
b := []byte(data)
diff := totalSize - len(b)
if diff > 0 {
var pChar string
if len(padChar) == 0 {
pChar = " "
} else {
pChar = string(padChar[0])
}
pad := strings.Repeat(pChar, diff)
if padRight {
result += pad
} else {
result = pad + result
}
}
// return result
return result
}
// PadLeft will pad data with space to the left
func PadLeft(data string, totalSize int) string {
return Padding(data, totalSize, false, " ")
}
// PadRight will pad data with space to the right
func PadRight(data string, totalSize int) string {
return Padding(data, totalSize, true, " ")
}
// PadZero pads zero to the left by default
func PadZero(data string, totalSize int, padRight ...bool) string {
right := GetFirstBoolOrDefault(false, padRight...)
return Padding(data, totalSize, right, "0")
}
// PadX pads X to the left by default
func PadX(data string, totalSize int, padRight ...bool) string {
right := GetFirstBoolOrDefault(false, padRight...)
return Padding(data, totalSize, right, "X")
}
// SplitString will split the source string using delimiter, and return the element indicated by index,
// if nothing is found, blank is returned,
// index = -1 returns last index
func SplitString(source string, delimiter string, index int) string {
ar := strings.Split(source, delimiter)
if len(ar) > 0 {
if index <= -1 {
return ar[len(ar)-1]
} else {
if len(ar) > index {
return ar[index]
} else {
return ""
}
}
}
return ""
}
// SliceStringToCSVString unboxes slice of string into comma separated string
func SliceStringToCSVString(source []string, spaceAfterComma bool) string {
output := ""
for _, v := range source {
if LenTrim(output) > 0 {
output += ","
if spaceAfterComma {
output += " "
}
}
output += v
}
return output
}
// ParseKeyValue will parse the input string using specified delimiter (= is default),
// result is set in the key and val fields
func ParseKeyValue(s string, delimiter string, key *string, val *string) error {
if len(s) <= 2 {
*key = ""
*val = ""
return fmt.Errorf("Source Data Must Exceed 2 Characters")
}
if len(delimiter) == 0 {
delimiter = "="
} else {
delimiter = string(delimiter[0])
}
if strings.Contains(s, delimiter) {
p := strings.Split(s, delimiter)
if len(p) == 2 {
*key = Trim(p[0])
*val = Trim(p[1])
return nil
}
// parts not valid
*key = ""
*val = ""
return fmt.Errorf("Parsed Parts Must Equal 2")
}
// no delimiter found
*key = ""
*val = ""
return fmt.Errorf("Delimiter Not Found in Source Data")
}
// ExtractNumeric will extract only 0-9 out of string to be returned
func ExtractNumeric(s string) (string, error) {
exp, err := regexp.Compile("[^0-9]+")
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ExtractAlpha will extract A-Z out of string to be returned
func ExtractAlpha(s string) (string, error) {
exp, err := regexp.Compile("[^A-Za-z]+")
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ExtractAlphaNumeric will extract only A-Z, a-z, and 0-9 out of string to be returned
func ExtractAlphaNumeric(s string) (string, error) {
exp, err := regexp.Compile("[^A-Za-z0-9]+")
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ExtractHex will extract only A-F, a-f, and 0-9 out of string to be returned
func ExtractHex(s string) (string, error) {
exp, err := regexp.Compile("[^A-Fa-f0-9]+")
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ExtractAlphaNumericUnderscoreDash will extract only A-Z, a-z, 0-9, _, - out of string to be returned
func ExtractAlphaNumericUnderscoreDash(s string) (string, error) {
exp, err := regexp.Compile("[^A-Za-z0-9_-]+")
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ExtractAlphaNumericPrintableSymbols will extra A-Z, a-z, 0-9, and printable symbols
func ExtractAlphaNumericPrintableSymbols(s string) (string, error) {
exp, err := regexp.Compile("[^ -~]+")
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ExtractByRegex will extract string based on regex expression,
// any regex match will be replaced with blank
func ExtractByRegex(s string, regexStr string) (string, error) {
exp, err := regexp.Compile(regexStr)
if err != nil {
return "", err
}
return exp.ReplaceAllString(s, ""), nil
}
// ================================================================================================================
// TYPE CHECK HELPERS
// ================================================================================================================
// IsAlphanumericOnly checks if the input string is A-Z, a-z, and 0-9 only
func IsAlphanumericOnly(s string) bool {
exp, err := regexp.Compile("[A-Za-z0-9]+")
if err != nil {
return false
}
if len(exp.ReplaceAllString(s, "")) > 0 {
// has non alphanumeric
return false
} else {
// alphanumeric only
return true
}
}
// IsAlphanumericAndSpaceOnly checks if the input string is A-Z, a-z, 0-9, and space
func IsAlphanumericAndSpaceOnly(s string) bool {
exp, err := regexp.Compile("[A-Za-z0-9 ]+")
if err != nil {
return false
}
if len(exp.ReplaceAllString(s, "")) > 0 {
// has non alphanumeric and space
return false
} else {
// alphanumeric and space only
return true
}
}
// IsBase64Only checks if the input string is a-z, A-Z, 0-9, +, /, =
func IsBase64Only(s string) bool {
exp, err := regexp.Compile("[A-Za-z0-9+/=]+")
if err != nil {
return false
}
if len(exp.ReplaceAllString(s, "")) > 0 {
// has non base 64
return false
} else {
// base 64 only
return true
}
}
// IsHexOnly checks if the input string is a-f, A-F, 0-9
func IsHexOnly(s string) bool {
exp, err := regexp.Compile("[A-Fa-f0-9]+")
if err != nil {
return false
}
if len(exp.ReplaceAllString(s, "")) > 0 {
// has non hex
return false
} else {
// hex only
return true
}
}
// IsNumericIntOnly checks if the input string is 0-9 only
func IsNumericIntOnly(s string) bool {
exp, err := regexp.Compile("[0-9]+")
if err != nil {
return false
}
if len(exp.ReplaceAllString(s, "")) > 0 {
// has non numeric
return false
} else {
// numeric only
return true
}
}
// IsNumericFloat64 checks if string is float
func IsNumericFloat64(s string, positiveOnly bool) bool {
if LenTrim(s) == 0 {
return false
}
if f, ok := ParseFloat64(s); !ok {
return false
} else {
if positiveOnly {
if f < 0 {
return false
} else {
return true
}
} else {
return true
}
}
}
// IsNumericIntAndNegativeSignOnly checks if the input string is 0-9 and possibly with lead negative sign only
func IsNumericIntAndNegativeSignOnly(s string) bool {
if len(s) == 0 {
return false
}
if !IsNumericIntOnly(Left(s, 1)) && Left(s, 1) != "-" {
return false
}
if len(s) > 1 {
v := Right(s, len(s)-1)
if !IsNumericIntOnly(v) {
return false
} else {
return true
}
} else {
if s == "-" {
return false
} else {
return true
}
}
}
// ================================================================================================================
// HEX HELPERS
// ================================================================================================================
// StringToHex converts string into hex
func StringToHex(data string) string {
return strings.ToUpper(hex.EncodeToString([]byte(data)))
}
// ByteToHex converts byte array into hex
func ByteToHex(data []byte) string {
return strings.ToUpper(hex.EncodeToString(data))
}
// HexToString converts hex data into string
func HexToString(hexData string) (string, error) {
data, err := hex.DecodeString(hexData)
if err != nil {
return "", err
}
return string(data), nil
}
// HexToByte converts hex data into byte array
func HexToByte(hexData string) ([]byte, error) {
data, err := hex.DecodeString(hexData)
if err != nil {
return []byte{}, err
}
return data, nil
}
// ================================================================================================================
// BASE64 HELPERS
// ================================================================================================================
// Base64StdEncode will encode given data into base 64 standard encoded string
func Base64StdEncode(data string) string {
return base64.StdEncoding.EncodeToString([]byte(data))
}
// Base64StdDecode will decode given data from base 64 standard encoded string
func Base64StdDecode(data string) (string, error) {
b, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return "", err
}
return string(b), nil
}
// Base64UrlEncode will encode given data into base 64 url encoded string
func Base64UrlEncode(data string) string {
return base64.URLEncoding.EncodeToString([]byte(data))
}
// Base64UrlDecode will decode given data from base 64 url encoded string
func Base64UrlDecode(data string) (string, error) {
b, err := base64.URLEncoding.DecodeString(data)
if err != nil {
return "", err
}
return string(b), nil
}
// ================================================================================================================
// HTML HELPERS
// ================================================================================================================
// HTMLDecode will unescape html tags and extended tags relevant to our apps
func HTMLDecode(s string) string {
buf := html.UnescapeString(s)
buf = strings.Replace(buf, "&#39;", "'", -1)
buf = strings.Replace(buf, "&lt;", "<", -1)
buf = strings.Replace(buf, "&gt;", ">", -1)
buf = strings.Replace(buf, "&quot;", "\"", -1)
buf = strings.Replace(buf, "&apos;", "'", -1)
buf = strings.Replace(buf, "&#169;", "©", -1)
buf = strings.Replace(buf, "'", "'", -1)
buf = strings.Replace(buf, "<", "<", -1)
buf = strings.Replace(buf, ">", ">", -1)
buf = strings.Replace(buf, """, "\"", -1)
buf = strings.Replace(buf, "'", "'", -1)
buf = strings.Replace(buf, "©", "©", -1)
buf = strings.Replace(buf, "<FS>", "=", -1)
buf = strings.Replace(buf, "<GS>", "\n", -1)
return buf
}
// HTMLEncode will escape html tags
func HTMLEncode(s string) string {
return html.EscapeString(s)
}
// ================================================================================================================
// XML HELPERS
// ================================================================================================================
// XMLToEscaped will escape the data whose xml special chars > < & % ' " are escaped into > < & % ' "
func XMLToEscaped(data string) string {
var r string
r = strings.Replace(data, "&", "&", -1)
r = strings.Replace(r, ">", ">", -1)
r = strings.Replace(r, "<", "<", -1)
r = strings.Replace(r, "%", "%", -1)
r = strings.Replace(r, "'", "'", -1)
r = strings.Replace(r, "\"", """, -1)
return r
}
// XMLFromEscaped will un-escape the data whose > < & % ' " are converted to > < & % ' "
func XMLFromEscaped(data string) string {
var r string
r = strings.Replace(data, "&", "&", -1)
r = strings.Replace(r, ">", ">", -1)
r = strings.Replace(r, "<", "<", -1)
r = strings.Replace(r, "%", "%", -1)
r = strings.Replace(r, "'", "'", -1)
r = strings.Replace(r, """, "\"", -1)
return r
}
// MarshalXMLCompact will accept an input variable, typically struct with xml struct tags, to serialize from object into xml string
//
// *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
//
// special struct field:
//
// XMLName xml.Name `xml:"ElementName"`
//
// struct xml tags:
//
// `xml:"AttributeName,attr"` or `xml:",attr"` <<< Attribute Instead of Element
// `xml:"ElementName"` <<< XML Element Name
// `xml:"OuterElementName>InnerElementName"` <<< Outer XML Grouping By OuterElementName
// `xml:",cdata"` <<< <![CDATA[...]]
// `xml:",innerxml"` <<< Write as Inner XML Verbatim and Not Subject to Marshaling
// `xml:",comment"` <<< Write as Comment, and Not Contain "--" Within Value
// `xml:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array)
// `xml:"-"` <<< Omit From XML Marshal
func MarshalXMLCompact(v interface{}) (string, error) {
if v == nil {
return "", fmt.Errorf("Object For XML Marshal Must Not Be Nil")
}
b, err := xml.Marshal(v)
if err != nil {
return "", err
}
return string(b), nil
}
// MarshalXMLIndent will accept an input variable, typically struct with xml struct tags, to serialize from object into xml string with indented formatting
//
// *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
//
// special struct field:
//
// XMLName xml.Name `xml:"ElementName"`
//
// struct xml tags:
//
// `xml:"AttributeName,attr"` or `xml:",attr"` <<< Attribute Instead of Element
// `xml:"ElementName"` <<< XML Element Name
// `xml:"OuterElementName>InnerElementName"` <<< Outer XML Grouping By OuterElementName
// `xml:",cdata"` <<< <![CDATA[...]]
// `xml:",innerxml"` <<< Write as Inner XML Verbatim and Not Subject to Marshaling
// `xml:",comment"` <<< Write as Comment, and Not Contain "--" Within Value
// `xml:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array)
// `xml:"-"` <<< Omit From XML Marshal
func MarshalXMLIndent(v interface{}) (string, error) {
if v == nil {
return "", fmt.Errorf("Object For XML Marshal Must Not Be Nil")
}
b, err := xml.MarshalIndent(v, "", " ")
if err != nil {
return "", err
}
return string(b), nil
}
// MarshalXML with option for indent or compact
func MarshalXML(v interface{}, indentXML bool) (string, error) {
if indentXML {
return MarshalXMLIndent(v)
} else {
return MarshalXMLCompact(v)
}
}
// UnmarshalXML will accept input xml data string and deserialize into target object indicated by parameter v
//
// *** PASS PARAMETER AS "&v" IN ORDER TO BE WRITABLE ***
//
// *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
//
// if unmarshal is successful, nil is returned, otherwise error info is returned
func UnmarshalXML(xmlData string, v interface{}) error {
if LenTrim(xmlData) == 0 {
return fmt.Errorf("XML Data is Required")
}
return xml.Unmarshal([]byte(xmlData), v)
}
// ================================================================================================================
// ENCODING JSON HELPERS
// ================================================================================================================
// JsonToEscaped will escape the data whose json special chars are escaped
func JsonToEscaped(data string) string {
var r string
r = strings.Replace(data, `\`, `\\`, -1)
r = ascii.EscapeNonPrintable(r)
return r
}
// JsonFromEscaped will unescape the json data that may be special character escaped
func JsonFromEscaped(data string) string {
var r string
r = strings.Replace(data, `\\`, `\`, -1)
r = ascii.UnescapeNonPrintable(r)
if Left(r, 1) == "\"" {
r = Right(r, len(r)-1)
}
if Right(r, 1) == "\"" {
r = Left(r, len(r)-1)
}
return r
}
// MarshalJSONCompact will accept an input variable, typically struct with json struct tags, to serialize from object into json string with compact formatting
//
// *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
//
// struct json tags:
//
// `json:"ElementName"` <<< JSON Element Name
// `json:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array)
// `json:"-"` <<< Omit From JSON Marshal
func MarshalJSONCompact(v interface{}) (string, error) {
if v == nil {
return "", fmt.Errorf("Object For JSON Marshal Must Not Be Nil")
}
b, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(b), nil
}
// MarshalJSONIndent will accept an input variable, typically struct with json struct tags, to serialize from object into json string with indented formatting
//
// *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
//
// struct json tags:
//
// `json:"ElementName"` <<< JSON Element Name
// `json:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array)
// `json:"-"` <<< Omit From JSON Marshal
func MarshalJSONIndent(v interface{}) (string, error) {
if v == nil {
return "", fmt.Errorf("Object For JSON Marshal Must Not Be Nil")
}
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return "", err
}
return string(b), nil
}
// UnmarshalJSON will accept input json data string and deserialize into target object indicated by parameter v
//
// *** PASS PARAMETER AS "&v" IN ORDER TO BE WRITABLE ***
// *** v interface{} MUST BE initialized first ***
// *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
//
// if unmarshal is successful, nil is returned, otherwise error info is returned
func UnmarshalJSON(jsonData string, v interface{}) error {
if LenTrim(jsonData) == 0 {
return fmt.Errorf("JSON Data is Required")
}
return json.Unmarshal([]byte(jsonData), v)
}