Skip to content

Commit

Permalink
unmarshal country codes to uppercase (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
lstmux authored Jul 24, 2023
1 parent 5b9c66d commit 5a238dd
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
6 changes: 4 additions & 2 deletions country/alpha2.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ func (code *Alpha2Code) UnmarshalJSON(data []byte) error {

enumValue := Alpha2Code(str)
if len(enumValue) != 0 {
if _, err := ByAlpha2CodeErr(enumValue); err != nil {
country, err := ByAlpha2CodeErr(enumValue)
if err != nil {
return err
}

*code = country.Alpha2Code()
}

*code = enumValue
return nil
}

Expand Down
6 changes: 4 additions & 2 deletions country/alpha3.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ func (code *Alpha3Code) UnmarshalJSON(data []byte) error {

enumValue := Alpha3Code(str)
if len(enumValue) != 0 {
if _, err := ByAlpha3CodeErr(enumValue); err != nil {
country, err := ByAlpha3CodeErr(enumValue)
if err != nil {
return err
}

*code = country.Alpha3Code()
}

*code = enumValue
return nil
}

Expand Down
10 changes: 10 additions & 0 deletions country/country_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,11 @@ func TestAlpha2CodeUnmarshalJson(t *testing.T) {
t.FailNow()
}

var lowercase Alpha2CodeStruct
if err := json.Unmarshal([]byte(fmt.Sprintf(`{"code":"%s"}`, "ca")), &lowercase); err != nil || lowercase.Alpha2Code != Canada.Alpha2Code() {
t.FailNow()
}

var wrongCode Alpha2CodeStruct
if err := json.Unmarshal([]byte(fmt.Sprintf(`{"code":"%s"}`, "wrong code")), &wrongCode); err == nil {
t.FailNow()
Expand All @@ -441,6 +446,11 @@ func TestAlpha3CodeUnmarshalJson(t *testing.T) {
t.FailNow()
}

var lowercase Alpha3CodeStruct
if err := json.Unmarshal([]byte(fmt.Sprintf(`{"code":"%s"}`, "can")), &lowercase); err != nil || lowercase.Alpha3Code != Canada.Alpha3Code() {
t.FailNow()
}

var wrongCode Alpha3CodeStruct
if err := json.Unmarshal([]byte(fmt.Sprintf(`{"code":"%s"}`, "wrong code")), &wrongCode); err == nil {
t.FailNow()
Expand Down

0 comments on commit 5a238dd

Please sign in to comment.