Skip to content

Commit

Permalink
Fix marshalling of URL wrapper with nil value.
Browse files Browse the repository at this point in the history
Signed-off-by: Peter Štibraný <pstibrany@gmail.com>
  • Loading branch information
pstibrany committed Jun 2, 2021
1 parent 48e11a7 commit 0f50e0c
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
10 changes: 9 additions & 1 deletion config/http_config.go
Expand Up @@ -94,6 +94,10 @@ func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&s); err != nil {
return err
}
if s == "" {
u.URL = nil
return nil
}

urlp, err := url.Parse(s)
if err != nil {
Expand All @@ -117,6 +121,10 @@ func (u *URL) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if s == "" {
u.URL = nil
return nil
}
urlp, err := url.Parse(s)
if err != nil {
return err
Expand All @@ -130,7 +138,7 @@ func (u URL) MarshalJSON() ([]byte, error) {
if u.URL != nil {
return json.Marshal(u.URL.String())
}
return nil, nil
return []byte("null"), nil
}

// OAuth2 is the oauth2 client configuration.
Expand Down
62 changes: 62 additions & 0 deletions config/http_config_test.go
Expand Up @@ -1302,6 +1302,68 @@ func TestMarshalURL(t *testing.T) {
}
}

func TestMarshalNilURL(t *testing.T) {
u := &URL{}

c, err := json.Marshal(u)
if err != nil {
t.Fatal(err)
}
if string(c) != "null" {
t.Fatalf("URL with nil value not properly marshaled into JSON, got %q", c)
}

c, err = yaml.Marshal(u)
if err != nil {
t.Fatal(err)
}
if string(c) != "null\n" {
t.Fatalf("URL with nil value not properly marshaled into JSON, got %q", c)
}
}

func TestUnmarshalNullURL(t *testing.T) {
b := []byte(`null`)
var u URL

err := json.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if u.URL != nil {
t.Fatalf("`null` literal not properly unmarshaled from JSON as URL, got %#v", u.URL)
}

err = yaml.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if u.URL != nil {
t.Fatalf("`null` literal not properly unmarshaled from YAML as URL, got %#v", u.URL)
}
}

func TestUnmarshalEmptyURL(t *testing.T) {
b := []byte(`""`)
var u URL

err := json.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if u.URL != nil {
t.Fatalf("empty string not properly unmarshaled from JSON as URL, got %#v", u.URL)
}

err = yaml.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if u.URL != nil {
t.Fatalf("empty string not properly unmarshaled from YAML as URL, got %#v", u.URL)
}
}

func TestUnmarshalURL(t *testing.T) {
b := []byte(`"http://example.com/a b"`)
var u URL
Expand Down

0 comments on commit 0f50e0c

Please sign in to comment.