Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add decode hooks for *url.URL #41

Merged
merged 1 commit into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions decode_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net"
"net/netip"
"net/url"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -176,6 +177,26 @@ func StringToTimeDurationHookFunc() DecodeHookFunc {
}
}

// StringToURLHookFunc returns a DecodeHookFunc that converts
// strings to *url.URL.
func StringToURLHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(&url.URL{}) {
return data, nil
}

// Convert it by parsing
return url.Parse(data.(string))
}
}

// StringToIPHookFunc returns a DecodeHookFunc that converts
// strings to net.IP
func StringToIPHookFunc() DecodeHookFunc {
Expand Down
30 changes: 30 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"math/big"
"net"
"net/netip"
"net/url"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -286,6 +287,35 @@ func TestStringToTimeDurationHookFunc(t *testing.T) {
}
}

func TestStringToURLHookFunc(t *testing.T) {
f := StringToURLHookFunc()

urlSample, _ := url.Parse("http://example.com")
urlValue := reflect.ValueOf(urlSample)
strValue := reflect.ValueOf("http://example.com")
cases := []struct {
f, t reflect.Value
result interface{}
err bool
}{
{reflect.ValueOf("http://example.com"), urlValue, urlSample, false},
{reflect.ValueOf("http ://example.com"), urlValue, (*url.URL)(nil), true},
{reflect.ValueOf("http://example.com"), strValue, "http://example.com", false},
}

for i, tc := range cases {
actual, err := DecodeHookExec(f, tc.f, tc.t)
if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}
if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}

func TestStringToTimeHookFunc(t *testing.T) {
strValue := reflect.ValueOf("5")
timeValue := reflect.ValueOf(time.Time{})
Expand Down
Loading