Skip to content

Commit 388e5bb

Browse files
committed
Add ParseControlURI
1 parent 3ee003a commit 388e5bb

File tree

3 files changed

+26
-9
lines changed

3 files changed

+26
-9
lines changed

jsonapi/control_uri.go

+19-8
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,30 @@ type ControlURI struct {
1616
}
1717

1818
func (u *ControlURI) UnmarshalText(text []byte) error {
19-
if len(text) == 0 {
20-
return fmt.Errorf("Control URI should not be empty.")
21-
}
22-
if text[len(text)-1] == '/' {
23-
return fmt.Errorf("Control URI should not contains trailing slash.")
24-
}
25-
if a, err := url.ParseRequestURI(string(text[:])); err != nil {
19+
if a, err := ParseControlURI(string(text[:])); err != nil {
2620
return err
2721
} else {
28-
u.URL = *a
22+
*u = *a
2923
}
3024
return nil
3125
}
26+
3227
func (u ControlURI) MarshalJSON() ([]byte, error) {
3328
return json.Marshal(u.String())
3429
}
30+
31+
func ParseControlURI(text string) (*ControlURI, error) {
32+
if len(text) == 0 {
33+
return nil, fmt.Errorf("Control URI should not be empty.")
34+
}
35+
if text[len(text)-1] == '/' {
36+
return nil, fmt.Errorf("Control URI should not contains trailing slash.")
37+
}
38+
if u, err := url.ParseRequestURI(text); err != nil {
39+
return nil, err
40+
} else {
41+
return &ControlURI{
42+
URL: *u,
43+
}, nil
44+
}
45+
}

jsonapi_test/control_uri_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package jsonapi_test
77

88
import (
9+
"net/url"
910
"testing"
1011

1112
"github.com/nextmn/json-api/jsonapi"
@@ -31,4 +32,10 @@ func TestControlURI(t *testing.T) {
3132
if err := u.UnmarshalText([]byte("http://[fd00::1]:8000")); err != nil {
3233
t.Errorf("URI with an IPv6 address and a port should be accepted")
3334
}
35+
36+
u.UnmarshalText([]byte("http://example.org"))
37+
cmp, _ := url.ParseRequestURI("http://example.org")
38+
if u.URL != *cmp {
39+
t.Errorf("Valid ControlURI should be unmarshaled the same as ParseRequestURI does")
40+
}
3441
}

jsonapi_test/message_with_error_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ func TestMessageWithError(t *testing.T) {
3636
if err != nil {
3737
t.Errorf("Could not marshal MessageWithError to json")
3838
}
39-
fmt.Println(string(j1))
4039

4140
if !bytes.Equal(j1, j2) {
4241
t.Errorf("Result of marshaling MessageWithError to json is incorrect")

0 commit comments

Comments
 (0)