-
Notifications
You must be signed in to change notification settings - Fork 121
/
numbers.go
53 lines (46 loc) · 1.26 KB
/
numbers.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
package openrtb
import (
"encoding/json"
"strconv"
)
// NumberOrString attempts to fix OpenRTB incompatibilities
// of exchanges. On decoding, it can handle numbers and strings.
// On encoding, it will generate a number, as intended by the
// standard.
type NumberOrString int
// UnmarshalJSON implements json.Unmarshaler
func (n *NumberOrString) UnmarshalJSON(data []byte) (err error) {
var v int
if len(data) > 2 && data[0] == '"' && data[len(data)-1] == '"' {
err = json.Unmarshal(data[1:len(data)-1], &v)
} else {
err = json.Unmarshal(data, &v)
}
if err != nil {
return err
}
*n = NumberOrString(v)
return nil
}
// StringOrNumber attempts to fix OpenRTB incompatibilities
// of exchanges. On decoding, it can handle numbers and strings.
// On encoding, it will generate a string, as intended by the
// standard.
type StringOrNumber string
// UnmarshalJSON implements json.Unmarshaler
func (n *StringOrNumber) UnmarshalJSON(data []byte) error {
if len(data) >= 2 && data[0] == '"' && data[len(data)-1] == '"' {
var v string
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*n = StringOrNumber(v)
} else {
var v int
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*n = StringOrNumber(strconv.Itoa(v))
}
return nil
}