Skip to content

Commit 9ca3a8f

Browse files
committed
[dev] helper type for better unmarshal
1 parent 79ce47a commit 9ca3a8f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

helper.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,19 @@ package etherscan
99

1010
import (
1111
"math/big"
12+
"strconv"
13+
"time"
1214
)
1315

16+
// compose adds input to param, whose key is tag
17+
// if input is nil, compose is a no-op.
18+
func compose(param map[string]interface{}, tag string, input interface{}) {
19+
if input == nil {
20+
return
21+
}
22+
param[tag] = input
23+
}
24+
1425
// M is a type shorthand for param input
1526
type M map[string]interface{}
1627

@@ -29,3 +40,41 @@ func (b *BigInt) UnmarshalText(text []byte) (err error) {
2940
*b = BigInt(*bigInt)
3041
return nil
3142
}
43+
44+
// MarshalText implements the encoding.TextMarshaler
45+
func (b *BigInt) MarshalText() (text []byte, err error) {
46+
return []byte(b.Int().String()), nil
47+
}
48+
49+
// Int returns b's *big.Int form
50+
func (b *BigInt) Int() *big.Int {
51+
return (*big.Int)(b)
52+
}
53+
54+
// Time is a wrapper over big.Int to implement only unmarshalText
55+
// for json decoding.
56+
type Time time.Time
57+
58+
// UnmarshalText implements the encoding.TextUnmarshaler interface.
59+
func (t *Time) UnmarshalText(text []byte) (err error) {
60+
input, err := strconv.ParseInt(string(text), 10, 64)
61+
if err != nil {
62+
err = wrapErr(err, "strconv.ParseInt")
63+
return
64+
}
65+
66+
var timestamp = time.Unix(input, 0)
67+
*t = Time(timestamp)
68+
69+
return nil
70+
}
71+
72+
// Time returns t's time.Time form
73+
func (t Time) Time() time.Time {
74+
return time.Time(t)
75+
}
76+
77+
// MarshalText implements the encoding.TextMarshaler
78+
func (t *Time) MarshalText() (text []byte, err error) {
79+
return []byte(strconv.FormatInt(t.Time().Unix(), 10)), nil
80+
}

0 commit comments

Comments
 (0)