Skip to content

Commit

Permalink
Merge pull request #41 from einzigartigerName/main
Browse files Browse the repository at this point in the history
Add decode hooks for *url.URL
  • Loading branch information
sagikazarmark authored Sep 20, 2024
2 parents ff5d967 + 3149d67 commit abbd7b4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
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

0 comments on commit abbd7b4

Please sign in to comment.