diff --git a/generic.go b/generic.go index 7c977b9..8d6f441 100644 --- a/generic.go +++ b/generic.go @@ -3,12 +3,20 @@ package monstersirenfetch import ( "encoding/json" "strconv" + "strings" ) // StringInt is a JSON string representing an integer. 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) { var v string err = json.Unmarshal(data, &v) diff --git a/generic_test.go b/generic_test.go index 84d4485..1d7f04c 100644 --- a/generic_test.go +++ b/generic_test.go @@ -18,6 +18,7 @@ func TestStringInt(t *testing.T) { val int }{ {"valid", nil, `"3735928559"`, 0xdeadbeef}, + {"valid pad", nil, `"0009"`, 9}, {"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1}, {"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1}, }