github.com/sleungcy/cli@v7.1.0+incompatible/types/null_int.go (about) 1 package types 2 3 import ( 4 "fmt" 5 "strconv" 6 7 "github.com/jessevdk/go-flags" 8 ) 9 10 const JsonNull = "null" 11 12 // NullInt is a wrapper around integer values that can be null or an integer. 13 // Use IsSet to check if the value is provided, instead of checking against 0. 14 type NullInt struct { 15 IsSet bool 16 Value int 17 } 18 19 // ParseStringValue is used to parse a user provided flag argument. 20 func (n *NullInt) ParseStringValue(val string) error { 21 if val == "" { 22 n.IsSet = false 23 n.Value = 0 24 return nil 25 } 26 27 intVal, err := strconv.Atoi(val) 28 if err != nil { 29 n.IsSet = false 30 n.Value = 0 31 return &flags.Error{ 32 Type: flags.ErrMarshal, 33 Message: fmt.Sprintf("invalid integer value `%s`", val), 34 } 35 } 36 37 n.Value = intVal 38 n.IsSet = true 39 40 return nil 41 } 42 43 // IsValidValue returns an error if the input value is not an integer. 44 func (n *NullInt) IsValidValue(val string) error { 45 return n.ParseStringValue(val) 46 } 47 48 // ParseIntValue is used to parse a user provided *int argument. 49 func (n *NullInt) ParseIntValue(val *int) { 50 if val == nil { 51 n.IsSet = false 52 n.Value = 0 53 return 54 } 55 56 n.Value = *val 57 n.IsSet = true 58 } 59 60 func (n *NullInt) UnmarshalFlag(val string) error { 61 return n.ParseStringValue(val) 62 } 63 64 func (n *NullInt) UnmarshalJSON(rawJSON []byte) error { 65 stringValue := string(rawJSON) 66 67 if stringValue == JsonNull { 68 n.Value = 0 69 n.IsSet = false 70 return nil 71 } 72 73 return n.ParseStringValue(stringValue) 74 } 75 76 func (n NullInt) MarshalJSON() ([]byte, error) { 77 if n.IsSet { 78 return []byte(fmt.Sprint(n.Value)), nil 79 } 80 return []byte(JsonNull), nil 81 }