UnmarshalJSON implements the json.Unmarshaler interface.
(b []byte)
| 123 | |
| 124 | // UnmarshalJSON implements the json.Unmarshaler interface. |
| 125 | func (t *Time) UnmarshalJSON(b []byte) error { |
| 126 | p := strings.Split(string(b), ".") |
| 127 | switch len(p) { |
| 128 | case 1: |
| 129 | v, err := strconv.ParseInt(string(p[0]), 10, 64) |
| 130 | if err != nil { |
| 131 | return err |
| 132 | } |
| 133 | *t = Time(v * second) |
| 134 | |
| 135 | case 2: |
| 136 | v, err := strconv.ParseInt(string(p[0]), 10, 64) |
| 137 | if err != nil { |
| 138 | return err |
| 139 | } |
| 140 | v *= second |
| 141 | |
| 142 | prec := dotPrecision - len(p[1]) |
| 143 | if prec < 0 { |
| 144 | p[1] = p[1][:dotPrecision] |
| 145 | } else if prec > 0 { |
| 146 | p[1] = p[1] + strings.Repeat("0", prec) |
| 147 | } |
| 148 | |
| 149 | va, err := strconv.ParseInt(p[1], 10, 32) |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | |
| 154 | // If the value was something like -0.1 the negative is lost in the |
| 155 | // parsing because of the leading zero, this ensures that we capture it. |
| 156 | if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 { |
| 157 | *t = Time(v+va) * -1 |
| 158 | } else { |
| 159 | *t = Time(v + va) |
| 160 | } |
| 161 | |
| 162 | default: |
| 163 | return fmt.Errorf("invalid time %q", string(b)) |
| 164 | } |
| 165 | return nil |
| 166 | } |
| 167 | |
| 168 | // Duration wraps time.Duration. It is used to parse the custom duration format |
| 169 | // from YAML. |