diff --git a/jsonapi/control_uri.go b/jsonapi/control_uri.go index 74a5607..47aa651 100644 --- a/jsonapi/control_uri.go +++ b/jsonapi/control_uri.go @@ -16,19 +16,30 @@ type ControlURI struct { } func (u *ControlURI) UnmarshalText(text []byte) error { - if len(text) == 0 { - return fmt.Errorf("Control URI should not be empty.") - } - if text[len(text)-1] == '/' { - return fmt.Errorf("Control URI should not contains trailing slash.") - } - if a, err := url.ParseRequestURI(string(text[:])); err != nil { + if a, err := ParseControlURI(string(text[:])); err != nil { return err } else { - u.URL = *a + *u = *a } return nil } + func (u ControlURI) MarshalJSON() ([]byte, error) { return json.Marshal(u.String()) } + +func ParseControlURI(text string) (*ControlURI, error) { + if len(text) == 0 { + return nil, fmt.Errorf("Control URI should not be empty.") + } + if text[len(text)-1] == '/' { + return nil, fmt.Errorf("Control URI should not contains trailing slash.") + } + if u, err := url.ParseRequestURI(text); err != nil { + return nil, err + } else { + return &ControlURI{ + URL: *u, + }, nil + } +} diff --git a/jsonapi_test/control_uri_test.go b/jsonapi_test/control_uri_test.go index 6ad570f..572453f 100644 --- a/jsonapi_test/control_uri_test.go +++ b/jsonapi_test/control_uri_test.go @@ -6,6 +6,7 @@ package jsonapi_test import ( + "net/url" "testing" "github.com/nextmn/json-api/jsonapi" @@ -31,4 +32,10 @@ func TestControlURI(t *testing.T) { if err := u.UnmarshalText([]byte("http://[fd00::1]:8000")); err != nil { t.Errorf("URI with an IPv6 address and a port should be accepted") } + + u.UnmarshalText([]byte("http://example.org")) + cmp, _ := url.ParseRequestURI("http://example.org") + if u.URL != *cmp { + t.Errorf("Valid ControlURI should be unmarshaled the same as ParseRequestURI does") + } } diff --git a/jsonapi_test/message_with_error_test.go b/jsonapi_test/message_with_error_test.go index cbf7821..0a8de67 100644 --- a/jsonapi_test/message_with_error_test.go +++ b/jsonapi_test/message_with_error_test.go @@ -36,7 +36,6 @@ func TestMessageWithError(t *testing.T) { if err != nil { t.Errorf("Could not marshal MessageWithError to json") } - fmt.Println(string(j1)) if !bytes.Equal(j1, j2) { t.Errorf("Result of marshaling MessageWithError to json is incorrect")