Skip to content

Commit

Permalink
add unmarshal to uri
Browse files Browse the repository at this point in the history
  • Loading branch information
negrel committed Sep 5, 2024
1 parent b060c95 commit 5f95b13
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/uri/uri.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,15 @@ func (u Uri) String() string {
func (u Uri) MarshalJSON() ([]byte, error) {
return json.Marshal(u.String())
}

// UnmarshalJSON implements json.Unmarshaler.
func (u *Uri) UnmarshalJSON(b []byte) error {
str := ""
err := json.Unmarshal(b, &str)
if err != nil {
return err
}

*u, err = Parse(str)
return err
}
28 changes: 28 additions & 0 deletions pkg/uri/uri_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package uri

import (
"encoding/json"
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -87,4 +89,30 @@ func TestUri(t *testing.T) {
require.Equal(t, "https://www.example.com/?q=foo#bar", uri.String())
})
})

t.Run("Json", func(t *testing.T) {
t.Run("Marshal", func(t *testing.T) {
uri, err := Parse("https://www.example.com?q=foo#bar")
require.NoError(t, err)

jsonUri, err := json.Marshal(uri)
require.NoError(t, err)

require.Equal(t, fmt.Sprintf("%q", uri.String()), string(jsonUri))
})

t.Run("Unmarshal", func(t *testing.T) {
uri, err := Parse("https://www.example.com?q=foo#bar")
require.NoError(t, err)

jsonUri, err := json.Marshal(uri)
require.NoError(t, err)

uri2 := Uri{}
err = json.Unmarshal(jsonUri, &uri2)
require.NoError(t, err)

require.Equal(t, uri, uri2)
})
})
}

0 comments on commit 5f95b13

Please sign in to comment.