@@ -2,12 +2,17 @@ package modifiers
22
33import (
44 "context"
5+ "reflect"
56 "strconv"
67 "time"
78
89 "github.com/go-playground/mold/v4"
910)
1011
12+ var (
13+ durationType = reflect .TypeOf (time .Duration (0 ))
14+ )
15+
1116//
1217// defaultValue allows setting of a default value IF no value is already present.
1318//
@@ -16,44 +21,56 @@ func defaultValue(ctx context.Context, fl mold.FieldLevel) error {
1621 return nil
1722 }
1823
19- switch fl .Field ().Interface ().( type ) {
20- case string :
24+ switch fl .Field ().Kind ( ) {
25+ case reflect . String :
2126 fl .Field ().SetString (fl .Param ())
2227
23- case int , int8 , int16 , int32 , int64 :
28+ case reflect . Int , reflect . Int8 , reflect . Int16 , reflect . Int32 :
2429 value , err := strconv .Atoi (fl .Param ())
2530 if err != nil {
2631 return err
2732 }
2833 fl .Field ().SetInt (int64 (value ))
2934
30- case uint , uint8 , uint16 , uint32 , uint64 :
35+ case reflect .Int64 :
36+ var value int64
37+
38+ if fl .Field ().Type () == durationType {
39+ d , err := time .ParseDuration (fl .Param ())
40+ if err != nil {
41+ return err
42+ }
43+ value = int64 (d )
44+ } else {
45+ i , err := strconv .Atoi (fl .Param ())
46+ if err != nil {
47+ return err
48+ }
49+ value = int64 (i )
50+ }
51+ fl .Field ().SetInt (value )
52+
53+ case reflect .Uint , reflect .Uint8 , reflect .Uint16 , reflect .Uint32 , reflect .Uint64 :
3154 value , err := strconv .Atoi (fl .Param ())
3255 if err != nil {
3356 return err
3457 }
3558 fl .Field ().SetUint (uint64 (value ))
3659
37- case float32 , float64 :
60+ case reflect . Float32 , reflect . Float64 :
3861 value , err := strconv .ParseFloat (fl .Param (), 64 )
3962 if err != nil {
4063 return err
4164 }
4265 fl .Field ().SetFloat (value )
4366
44- case bool :
67+ case reflect . Bool :
4568 value , err := strconv .ParseBool (fl .Param ())
4669 if err != nil {
4770 return err
4871 }
4972 fl .Field ().SetBool (value )
5073
51- case time.Duration :
52- d , err := time .ParseDuration (fl .Param ())
53- if err != nil {
54- return err
55- }
56- fl .Field ().SetInt (int64 (d ))
5774 }
5875 return nil
5976}
0 commit comments