-
Notifications
You must be signed in to change notification settings - Fork 5
/
helper-struct.go
2257 lines (1976 loc) · 70.5 KB
/
helper-struct.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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package helper
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/url"
"reflect"
"strings"
"time"
)
/*
* 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.
*/
// Fill copies the src struct with same tag name to dst struct tag pointer,
// src and dst both must be struct,and dst must be pointer
func Fill(src interface{}, dst interface{}) error {
srcType := reflect.TypeOf(src)
srcValue := reflect.ValueOf(src)
dstValue := reflect.ValueOf(dst)
if srcType.Kind() != reflect.Struct {
return errors.New("src must be struct")
}
if dstValue.Kind() != reflect.Ptr {
return errors.New("dst must be point")
}
for i := 0; i < srcType.NumField(); i++ {
dstField := dstValue.Elem().FieldByName(srcType.Field(i).Name)
if dstField.CanSet() {
dstField.Set(srcValue.Field(i))
}
}
return nil
}
// MarshalStructToQueryParams marshals a struct pointer's fields to query params string,
// output query param names are based on values given in tagName,
// to exclude certain struct fields from being marshaled, use - as value in struct tag defined by tagName,
// if there is a need to name the value of tagName, but still need to exclude from output, use the excludeTagName with -, such as `x:"-"`
//
// special struct tags:
// 1. `getter:"Key"` // if field type is custom struct or enum,
// specify the custom method getter (no parameters allowed) that returns the expected value in first ordinal result position
// NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke
// NOTE: if the method is to receive a parameter value, always in string data type, add '(x)' after the method name, such as 'XYZ(x)' or 'base.XYZ(x)'
// 2. `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value,
// if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
// 3. `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value
// if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
// 4. `uniqueid:"xyz"` // if two or more struct field is set with the same uniqueid, then only the first encountered field with the same uniqueid will be used in marshal
// 5. `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
// 6. `skipzero:"false"` // if true, then any fields that are 0, 0.00, time.Zero(), false, nil will be excluded from marshal (this only affects fields that are number, bool, time, pointer)
// 7. `timeformat:"20060102"` // for time.Time field, optional date time format, specified as:
// 2006, 06 = year,
// 01, 1, Jan, January = month,
// 02, 2, _2 = day (_2 = width two, right justified)
// 03, 3, 15 = hour (15 = 24 hour format)
// 04, 4 = minute
// 05, 5 = second
// PM pm = AM PM
// 8. `outprefix:""` // for marshal method, if field value is to precede with an output prefix, such as XYZ= (affects marshal queryParams / csv methods only)
// 9. `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero
func MarshalStructToQueryParams(inputStructPtr interface{}, tagName string, excludeTagName string) (string, error) {
if inputStructPtr == nil {
return "", fmt.Errorf("MarshalStructToQueryParams Requires Input Struct Variable Pointer")
}
if LenTrim(tagName) == 0 {
return "", fmt.Errorf("MarshalStructToQueryParams Requires TagName (Tag Name defines query parameter name)")
}
s := reflect.ValueOf(inputStructPtr)
if s.Kind() != reflect.Ptr {
return "", fmt.Errorf("MarshalStructToQueryParams Expects inputStructPtr To Be a Pointer")
} else {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return "", fmt.Errorf("MarshalStructToQueryParams Requires Struct Object")
}
output := ""
uniqueMap := make(map[string]string)
for i := 0; i < s.NumField(); i++ {
field := s.Type().Field(i)
if o := s.FieldByName(field.Name); o.IsValid() {
tag := field.Tag.Get(tagName)
if LenTrim(tag) == 0 {
tag = field.Name
}
if tag != "-" {
if LenTrim(excludeTagName) > 0 {
if Trim(field.Tag.Get(excludeTagName)) == "-" {
continue
}
}
if tagUniqueId := Trim(field.Tag.Get("uniqueid")); len(tagUniqueId) > 0 {
if _, ok := uniqueMap[strings.ToLower(tagUniqueId)]; ok {
continue
} else {
uniqueMap[strings.ToLower(tagUniqueId)] = field.Name
}
}
var boolTrue, boolFalse, timeFormat, outPrefix string
var skipBlank, skipZero, zeroblank bool
if vs := GetStructTagsValueSlice(field, "booltrue", "boolfalse", "skipblank", "skipzero", "timeformat", "outprefix", "zeroblank"); len(vs) == 7 {
boolTrue = vs[0]
boolFalse = vs[1]
skipBlank, _ = ParseBool(vs[2])
skipZero, _ = ParseBool(vs[3])
timeFormat = vs[4]
outPrefix = vs[5]
zeroblank, _ = ParseBool(vs[6])
}
oldVal := o
if tagGetter := Trim(field.Tag.Get("getter")); len(tagGetter) > 0 {
isBase := false
useParam := false
paramVal := ""
var paramSlice interface{}
if strings.ToLower(Left(tagGetter, 5)) == "base." {
isBase = true
tagGetter = Right(tagGetter, len(tagGetter)-5)
}
if strings.ToLower(Right(tagGetter, 3)) == "(x)" {
useParam = true
if o.Kind() != reflect.Slice {
paramVal, _, _ = ReflectValueToString(o, boolTrue, boolFalse, skipBlank, skipZero, timeFormat, zeroblank)
} else {
if o.Len() > 0 {
paramSlice = o.Slice(0, o.Len()).Interface()
}
}
tagGetter = Left(tagGetter, len(tagGetter)-3)
}
var ov []reflect.Value
var notFound bool
if isBase {
if useParam {
if paramSlice == nil {
ov, notFound = ReflectCall(s.Addr(), tagGetter, paramVal)
} else {
ov, notFound = ReflectCall(s.Addr(), tagGetter, paramSlice)
}
} else {
ov, notFound = ReflectCall(s.Addr(), tagGetter)
}
} else {
if useParam {
if paramSlice == nil {
ov, notFound = ReflectCall(o, tagGetter, paramVal)
} else {
ov, notFound = ReflectCall(o, tagGetter, paramSlice)
}
} else {
ov, notFound = ReflectCall(o, tagGetter)
}
}
if !notFound {
if len(ov) > 0 {
o = ov[0]
}
}
}
if buf, skip, err := ReflectValueToString(o, boolTrue, boolFalse, skipBlank, skipZero, timeFormat, zeroblank); err != nil || skip {
if tagUniqueId := Trim(field.Tag.Get("uniqueid")); len(tagUniqueId) > 0 {
if _, ok := uniqueMap[strings.ToLower(tagUniqueId)]; ok {
delete(uniqueMap, strings.ToLower(tagUniqueId))
}
}
continue
} else {
defVal := field.Tag.Get("def")
if oldVal.Kind() == reflect.Int && oldVal.Int() == 0 && strings.ToLower(buf) == "unknown" {
// unknown enum value will be serialized as blank
buf = ""
if len(defVal) > 0 {
buf = defVal
} else {
if tagUniqueId := Trim(field.Tag.Get("uniqueid")); len(tagUniqueId) > 0 {
if _, ok := uniqueMap[strings.ToLower(tagUniqueId)]; ok {
// remove uniqueid if skip
delete(uniqueMap, strings.ToLower(tagUniqueId))
continue
}
}
}
}
if boolFalse == " " && len(outPrefix) > 0 && buf == "false" {
buf = ""
} else {
if len(buf) == 0 && len(defVal) > 0 {
buf = defVal
}
if skipBlank && LenTrim(buf) == 0 {
buf = ""
} else if skipZero && buf == "0" {
buf = ""
} else {
buf = outPrefix + buf
}
}
if LenTrim(output) > 0 {
output += "&"
}
output += fmt.Sprintf("%s=%s", tag, url.PathEscape(buf))
}
}
}
}
if LenTrim(output) == 0 {
return "", fmt.Errorf("MarshalStructToQueryParams Yielded Blank Output")
} else {
return output, nil
}
}
// MarshalStructToJson marshals a struct pointer's fields to json string,
// output json names are based on values given in tagName,
// to exclude certain struct fields from being marshaled, include - as value in struct tag defined by tagName,
// if there is a need to name the value of tagName, but still need to exclude from output, use the excludeTagName with -, such as `x:"-"`
//
// special struct tags:
// 1. `getter:"Key"` // if field type is custom struct or enum,
// specify the custom method getter (no parameters allowed) that returns the expected value in first ordinal result position
// NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke
// NOTE: if the method is to receive a parameter value, always in string data type, add '(x)' after the method name, such as 'XYZ(x)' or 'base.XYZ(x)'
// 2. `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value
// if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
// 3. `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value
// if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
// 4. `uniqueid:"xyz"` // if two or more struct field is set with the same uniqueid, then only the first encountered field with the same uniqueid will be used in marshal
// 5. `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
// 6. `skipzero:"false"` // if true, then any fields that are 0, 0.00, time.Zero(), false, nil will be excluded from marshal (this only affects fields that are number, bool, time, pointer)
// 7. `timeformat:"20060102"` // for time.Time field, optional date time format, specified as:
// 2006, 06 = year,
// 01, 1, Jan, January = month,
// 02, 2, _2 = day (_2 = width two, right justified)
// 03, 3, 15 = hour (15 = 24 hour format)
// 04, 4 = minute
// 05, 5 = second
// PM pm = AM PM
// 8. `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero
func MarshalStructToJson(inputStructPtr interface{}, tagName string, excludeTagName string) (string, error) {
if inputStructPtr == nil {
return "", fmt.Errorf("MarshalStructToJson Requires Input Struct Variable Pointer")
}
if LenTrim(tagName) == 0 {
return "", fmt.Errorf("MarshalStructToJson Requires TagName (Tag Name defines Json name)")
}
s := reflect.ValueOf(inputStructPtr)
if s.Kind() != reflect.Ptr {
return "", fmt.Errorf("MarshalStructToJson Expects inputStructPtr To Be a Pointer")
} else {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return "", fmt.Errorf("MarshalStructToJson Requires Struct Object")
}
output := ""
uniqueMap := make(map[string]string)
for i := 0; i < s.NumField(); i++ {
field := s.Type().Field(i)
if o := s.FieldByName(field.Name); o.IsValid() {
tag := field.Tag.Get(tagName)
if LenTrim(tag) == 0 {
tag = field.Name
}
if tag != "-" {
if LenTrim(excludeTagName) > 0 {
if Trim(field.Tag.Get(excludeTagName)) == "-" {
continue
}
}
if tagUniqueId := Trim(field.Tag.Get("uniqueid")); len(tagUniqueId) > 0 {
if _, ok := uniqueMap[strings.ToLower(tagUniqueId)]; ok {
continue
} else {
uniqueMap[strings.ToLower(tagUniqueId)] = field.Name
}
}
var boolTrue, boolFalse, timeFormat string
var skipBlank, skipZero, zeroBlank bool
if vs := GetStructTagsValueSlice(field, "booltrue", "boolfalse", "skipblank", "skipzero", "timeformat", "zeroblank"); len(vs) == 6 {
boolTrue = vs[0]
boolFalse = vs[1]
skipBlank, _ = ParseBool(vs[2])
skipZero, _ = ParseBool(vs[3])
timeFormat = vs[4]
zeroBlank, _ = ParseBool(vs[5])
}
oldVal := o
if tagGetter := Trim(field.Tag.Get("getter")); len(tagGetter) > 0 {
isBase := false
useParam := false
paramVal := ""
var paramSlice interface{}
if strings.ToLower(Left(tagGetter, 5)) == "base." {
isBase = true
tagGetter = Right(tagGetter, len(tagGetter)-5)
}
if strings.ToLower(Right(tagGetter, 3)) == "(x)" {
useParam = true
if o.Kind() != reflect.Slice {
paramVal, _, _ = ReflectValueToString(o, boolTrue, boolFalse, skipBlank, skipZero, timeFormat, zeroBlank)
} else {
if o.Len() > 0 {
paramSlice = o.Slice(0, o.Len()).Interface()
}
}
tagGetter = Left(tagGetter, len(tagGetter)-3)
}
var ov []reflect.Value
var notFound bool
if isBase {
if useParam {
if paramSlice == nil {
ov, notFound = ReflectCall(s.Addr(), tagGetter, paramVal)
} else {
ov, notFound = ReflectCall(s.Addr(), tagGetter, paramSlice)
}
} else {
ov, notFound = ReflectCall(s.Addr(), tagGetter)
}
} else {
if useParam {
if paramSlice == nil {
ov, notFound = ReflectCall(o, tagGetter, paramVal)
} else {
ov, notFound = ReflectCall(o, tagGetter, paramSlice)
}
} else {
ov, notFound = ReflectCall(o, tagGetter)
}
}
if !notFound {
if len(ov) > 0 {
o = ov[0]
}
}
}
buf, skip, err := ReflectValueToString(o, boolTrue, boolFalse, skipBlank, skipZero, timeFormat, zeroBlank)
if err != nil || skip {
if tagUniqueId := Trim(field.Tag.Get("uniqueid")); len(tagUniqueId) > 0 {
if _, ok := uniqueMap[strings.ToLower(tagUniqueId)]; ok {
delete(uniqueMap, strings.ToLower(tagUniqueId))
}
}
continue
}
defVal := field.Tag.Get("def")
if oldVal.Kind() == reflect.Int && oldVal.Int() == 0 && strings.ToLower(buf) == "unknown" {
// unknown enum value will be serialized as blank
buf = ""
if len(defVal) > 0 {
buf = defVal
} else {
if tagUniqueId := Trim(field.Tag.Get("uniqueid")); len(tagUniqueId) > 0 {
if _, ok := uniqueMap[strings.ToLower(tagUniqueId)]; ok {
// remove uniqueid if skip
delete(uniqueMap, strings.ToLower(tagUniqueId))
continue
}
}
}
}
outPrefix := field.Tag.Get("outprefix")
if boolTrue == " " && len(buf) == 0 && len(outPrefix) > 0 {
buf = outPrefix + defVal
} else if boolFalse == " " && buf == "false" && len(outPrefix) > 0 {
buf = ""
} else if len(defVal) > 0 && len(buf) == 0 {
buf = outPrefix + defVal
}
buf = strings.Replace(buf, `"`, `\"`, -1)
buf = strings.Replace(buf, `'`, `\'`, -1)
if LenTrim(output) > 0 {
output += ", "
}
output += fmt.Sprintf(`"%s":"%s"`, tag, JsonToEscaped(buf))
}
}
}
if LenTrim(output) == 0 {
return "", fmt.Errorf("MarshalStructToJson Yielded Blank Output")
} else {
return fmt.Sprintf("{%s}", output), nil
}
}
// UnmarshalJsonToStruct will parse jsonPayload string,
// and set parsed json element value into struct fields based on struct tag named by tagName,
// any tagName value with - will be ignored, any excludeTagName defined with value of - will also cause parser to ignore the field
//
// note: this method expects simple json in key value pairs only, not json containing slices or more complex json structs within existing json field
//
// Predefined Struct Tags Usable:
// 1. `setter:"ParseByKey` // if field type is custom struct or enum,
// specify the custom method (only 1 lookup parameter value allowed) setter that sets value(s) into the field
// NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke
// NOTE: setter method always intake a string parameter
// 2. `def:""` // default value to set into struct field in case unmarshal doesn't set the struct field value
// 3. `timeformat:"20060102"` // for time.Time field, optional date time format, specified as:
// 2006, 06 = year,
// 01, 1, Jan, January = month,
// 02, 2, _2 = day (_2 = width two, right justified)
// 03, 3, 15 = hour (15 = 24 hour format)
// 04, 4 = minute
// 05, 5 = second
// PM pm = AM PM
// 4. `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value,
// if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
// 5. `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value
// if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
func UnmarshalJsonToStruct(inputStructPtr interface{}, jsonPayload string, tagName string, excludeTagName string) error {
if inputStructPtr == nil {
return fmt.Errorf("InputStructPtr is Required")
}
if LenTrim(jsonPayload) == 0 {
return fmt.Errorf("JsonPayload is Required")
}
if LenTrim(tagName) == 0 {
return fmt.Errorf("TagName is Required")
}
s := reflect.ValueOf(inputStructPtr)
if s.Kind() != reflect.Ptr {
return fmt.Errorf("InputStructPtr Must Be Pointer")
} else {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return fmt.Errorf("InputStructPtr Must Be Struct")
}
// unmarshal json to map
jsonMap := make(map[string]json.RawMessage)
if err := json.Unmarshal([]byte(jsonPayload), &jsonMap); err != nil {
return fmt.Errorf("Unmarshal Json Failed: %s", err)
}
if jsonMap == nil {
return fmt.Errorf("Unmarshaled Json Map is Nil")
}
if len(jsonMap) == 0 {
return fmt.Errorf("Unmarshaled Json Map Has No Elements")
}
StructClearFields(inputStructPtr)
SetStructFieldDefaultValues(inputStructPtr)
for i := 0; i < s.NumField(); i++ {
field := s.Type().Field(i)
if o := s.FieldByName(field.Name); o.IsValid() && o.CanSet() {
// get json field name if defined
jName := Trim(field.Tag.Get(tagName))
if jName == "-" {
continue
}
if LenTrim(excludeTagName) > 0 {
if Trim(field.Tag.Get(excludeTagName)) == "-" {
continue
}
}
if LenTrim(jName) == 0 {
jName = field.Name
}
// get json field value based on jName from jsonMap
jValue := ""
timeFormat := Trim(field.Tag.Get("timeformat"))
if jRaw, ok := jsonMap[jName]; !ok {
continue
} else {
jValue = JsonFromEscaped(string(jRaw))
if len(jValue) > 0 {
if tagSetter := Trim(field.Tag.Get("setter")); len(tagSetter) > 0 {
isBase := false
if strings.ToLower(Left(tagSetter, 5)) == "base." {
isBase = true
tagSetter = Right(tagSetter, len(tagSetter)-5)
}
if o.Kind() != reflect.Ptr && o.Kind() != reflect.Interface && o.Kind() != reflect.Struct && o.Kind() != reflect.Slice {
// o is not ptr, interface, struct
var results []reflect.Value
var notFound bool
if isBase {
results, notFound = ReflectCall(s.Addr(), tagSetter, jValue)
} else {
results, notFound = ReflectCall(o, tagSetter, jValue)
}
if !notFound && len(results) > 0 {
if len(results) == 1 {
if jv, _, err := ReflectValueToString(results[0], "", "", false, false, timeFormat, false); err == nil {
jValue = jv
}
} else if len(results) > 1 {
getFirstVar := true
if e, ok := results[len(results)-1].Interface().(error); ok {
// last var is error, check if error exists
if e != nil {
getFirstVar = false
}
}
if getFirstVar {
if jv, _, err := ReflectValueToString(results[0], "", "", false, false, timeFormat, false); err == nil {
jValue = jv
}
}
}
}
} else {
// o is ptr, interface, struct
// get base type
if o.Kind() != reflect.Slice {
if baseType, _, isNilPtr := DerefPointersZero(o); isNilPtr {
// create new struct pointer
o.Set(reflect.New(baseType.Type()))
} else {
if o.Kind() == reflect.Interface && o.Interface() == nil {
customType := ReflectTypeRegistryGet(o.Type().String())
if customType == nil {
return fmt.Errorf("%s Struct Field %s is Interface Without Actual Object Assignment", s.Type(), o.Type())
} else {
o.Set(reflect.New(customType))
}
}
}
}
var ov []reflect.Value
var notFound bool
if isBase {
ov, notFound = ReflectCall(s.Addr(), tagSetter, jValue)
} else {
ov, notFound = ReflectCall(o, tagSetter, jValue)
}
if !notFound {
if len(ov) == 1 {
if ov[0].Kind() == reflect.Ptr || ov[0].Kind() == reflect.Slice {
o.Set(ov[0])
}
} else if len(ov) > 1 {
getFirstVar := true
if e := DerefError(ov[len(ov)-1]); e != nil {
getFirstVar = false
}
if getFirstVar {
if ov[0].Kind() == reflect.Ptr || ov[0].Kind() == reflect.Slice {
o.Set(ov[0])
}
}
}
}
// for o as ptr
// once complete, continue
continue
}
}
}
}
// set validated csv value into corresponding struct field
outPrefix := field.Tag.Get("outprefix")
boolTrue := field.Tag.Get("booltrue")
boolFalse := field.Tag.Get("boolfalse")
if boolTrue == " " && len(outPrefix) > 0 && jValue == outPrefix {
jValue = "true"
} else {
evalOk := false
if LenTrim(boolTrue) > 0 && len(jValue) > 0 && boolTrue == jValue {
jValue = "true"
evalOk = true
}
if !evalOk {
if LenTrim(boolFalse) > 0 && len(jValue) > 0 && boolFalse == jValue {
jValue = "false"
}
}
}
if err := ReflectStringToField(o, jValue, timeFormat); err != nil {
return err
}
}
}
return nil
}
// MarshalSliceStructToJson accepts a slice of struct pointer, then using tagName and excludeTagName to marshal to json array
// To pass in inputSliceStructPtr, convert slice of actual objects at the calling code, using SliceObjectsToSliceInterface(),
// if there is a need to name the value of tagName, but still need to exclude from output, use the excludeTagName with -, such as `x:"-"`
func MarshalSliceStructToJson(inputSliceStructPtr []interface{}, tagName string, excludeTagName string) (jsonArrayOutput string, err error) {
if len(inputSliceStructPtr) == 0 {
return "", fmt.Errorf("Input Slice Struct Pointer Nil")
}
for _, v := range inputSliceStructPtr {
if s, e := MarshalStructToJson(v, tagName, excludeTagName); e != nil {
return "", fmt.Errorf("MarshalSliceStructToJson Failed: %s", e)
} else {
if LenTrim(jsonArrayOutput) > 0 {
jsonArrayOutput += ", "
}
jsonArrayOutput += s
}
}
if LenTrim(jsonArrayOutput) > 0 {
return fmt.Sprintf("[%s]", jsonArrayOutput), nil
} else {
return "", fmt.Errorf("MarshalSliceStructToJson Yielded Blank String")
}
}
// StructClearFields will clear all fields within struct with default value
func StructClearFields(inputStructPtr interface{}) {
if inputStructPtr == nil {
return
}
s := reflect.ValueOf(inputStructPtr)
if s.Kind() != reflect.Ptr {
return
} else {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return
}
for i := 0; i < s.NumField(); i++ {
field := s.Type().Field(i)
if o := s.FieldByName(field.Name); o.IsValid() && o.CanSet() {
switch o.Kind() {
case reflect.String:
o.SetString("")
case reflect.Bool:
o.SetBool(false)
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
o.SetInt(0)
case reflect.Float32:
fallthrough
case reflect.Float64:
o.SetFloat(0)
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
o.SetUint(0)
case reflect.Ptr:
o.Set(reflect.Zero(o.Type()))
case reflect.Slice:
o.Set(reflect.Zero(o.Type()))
default:
switch o.Interface().(type) {
case sql.NullString:
o.Set(reflect.ValueOf(sql.NullString{}))
case sql.NullBool:
o.Set(reflect.ValueOf(sql.NullBool{}))
case sql.NullFloat64:
o.Set(reflect.ValueOf(sql.NullFloat64{}))
case sql.NullInt32:
o.Set(reflect.ValueOf(sql.NullInt32{}))
case sql.NullInt64:
o.Set(reflect.ValueOf(sql.NullInt64{}))
case sql.NullTime:
o.Set(reflect.ValueOf(sql.NullTime{}))
case time.Time:
o.Set(reflect.ValueOf(time.Time{}))
default:
o.Set(reflect.Zero(o.Type()))
}
}
}
}
}
// StructNonDefaultRequiredFieldsCount returns count of struct fields that are tagged as required but not having any default values pre-set
func StructNonDefaultRequiredFieldsCount(inputStructPtr interface{}) int {
if inputStructPtr == nil {
return 0
}
s := reflect.ValueOf(inputStructPtr)
if s.Kind() != reflect.Ptr {
return 0
} else {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return 0
}
count := 0
for i := 0; i < s.NumField(); i++ {
field := s.Type().Field(i)
if o := s.FieldByName(field.Name); o.IsValid() && o.CanSet() {
tagDef := field.Tag.Get("def")
tagReq := field.Tag.Get("req")
if len(tagDef) == 0 && strings.ToLower(tagReq) == "true" {
// required and no default value
count++
}
}
}
return count
}
// IsStructFieldSet checks if any field value is not default blank or zero
func IsStructFieldSet(inputStructPtr interface{}) bool {
if inputStructPtr == nil {
return false
}
s := reflect.ValueOf(inputStructPtr)
if s.Kind() != reflect.Ptr {
return false
} else {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return false
}
for i := 0; i < s.NumField(); i++ {
field := s.Type().Field(i)
if o := s.FieldByName(field.Name); o.IsValid() && o.CanSet() {
tagDef := field.Tag.Get("def")
switch o.Kind() {
case reflect.String:
if LenTrim(o.String()) > 0 {
if o.String() != tagDef {
return true
}
}
case reflect.Bool:
if o.Bool() {
return true
}
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
if o.Int() != 0 {
if Int64ToString(o.Int()) != tagDef {
return true
}
}
case reflect.Float32:
fallthrough
case reflect.Float64:
if o.Float() != 0 {
if Float64ToString(o.Float()) != tagDef {
return true
}
}
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
if o.Uint() > 0 {
if UInt64ToString(o.Uint()) != tagDef {
return true
}
}
case reflect.Ptr:
if !o.IsNil() {
return true
}
case reflect.Slice:
if o.Len() > 0 {
return true
}
default:
switch f := o.Interface().(type) {
case sql.NullString:
if f.Valid {
if len(tagDef) == 0 {
return true
} else {
if f.String != tagDef {
return true
}
}
}
case sql.NullBool:
if f.Valid {
if len(tagDef) == 0 {
return true
} else {
if f.Bool, _ = ParseBool(tagDef); f.Bool {
return true
}
}
}
case sql.NullFloat64:
if f.Valid {
if len(tagDef) == 0 {
return true
} else {
if Float64ToString(f.Float64) != tagDef {
return true
}
}
}
case sql.NullInt32:
if f.Valid {
if len(tagDef) == 0 {
return true
} else {
if Itoa(int(f.Int32)) != tagDef {
return true
}
}
}
case sql.NullInt64:
if f.Valid {
if len(tagDef) == 0 {
return true
} else {
if Int64ToString(f.Int64) != tagDef {
return true
}
}
}
case sql.NullTime:
if f.Valid {
if len(tagDef) == 0 {
return true
} else {
tagTimeFormat := Trim(field.Tag.Get("timeformat"))
if LenTrim(tagTimeFormat) == 0 {
tagTimeFormat = DateTimeFormatString()
}
if f.Time != ParseDateTimeCustom(tagDef, tagTimeFormat) {
return true
}
}
}
case time.Time:
if !f.IsZero() {
if len(tagDef) == 0 {
return true
} else {
tagTimeFormat := Trim(field.Tag.Get("timeformat"))
if LenTrim(tagTimeFormat) == 0 {
tagTimeFormat = DateTimeFormatString()
}
if f != ParseDateTimeCustom(tagDef, tagTimeFormat) {
return true
}
}
}