generic: pad string representation
This replicates api behaviour. Signed-off-by: Yonah <contrib@gensokyo.uk>
This commit is contained in:
parent
5b9d1e4fe8
commit
cc45f04800
10
generic.go
10
generic.go
@ -3,12 +3,20 @@ package monstersirenfetch
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// StringInt is a JSON string representing an integer.
|
// StringInt is a JSON string representing an integer.
|
||||||
type StringInt int
|
type StringInt int
|
||||||
|
|
||||||
func (i *StringInt) MarshalJSON() ([]byte, error) { return json.Marshal(strconv.Itoa(int(*i))) }
|
func (i *StringInt) MarshalJSON() ([]byte, error) {
|
||||||
|
s := strconv.Itoa(int(*i))
|
||||||
|
if len(s) < 4 {
|
||||||
|
s = strings.Repeat("0", 4-len(s)) + s
|
||||||
|
}
|
||||||
|
return json.Marshal(s)
|
||||||
|
}
|
||||||
|
|
||||||
func (i *StringInt) UnmarshalJSON(data []byte) (err error) {
|
func (i *StringInt) UnmarshalJSON(data []byte) (err error) {
|
||||||
var v string
|
var v string
|
||||||
err = json.Unmarshal(data, &v)
|
err = json.Unmarshal(data, &v)
|
||||||
|
@ -18,6 +18,7 @@ func TestStringInt(t *testing.T) {
|
|||||||
val int
|
val int
|
||||||
}{
|
}{
|
||||||
{"valid", nil, `"3735928559"`, 0xdeadbeef},
|
{"valid", nil, `"3735928559"`, 0xdeadbeef},
|
||||||
|
{"valid pad", nil, `"0009"`, 9},
|
||||||
{"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1},
|
{"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1},
|
||||||
{"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1},
|
{"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1},
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user