Skip to content

Commit abbd7b4

Browse files
Merge pull request #41 from einzigartigerName/main
Add decode hooks for *url.URL
2 parents ff5d967 + 3149d67 commit abbd7b4

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

decode_hooks.go

+21
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"net"
88
"net/netip"
9+
"net/url"
910
"reflect"
1011
"strconv"
1112
"strings"
@@ -176,6 +177,26 @@ func StringToTimeDurationHookFunc() DecodeHookFunc {
176177
}
177178
}
178179

180+
// StringToURLHookFunc returns a DecodeHookFunc that converts
181+
// strings to *url.URL.
182+
func StringToURLHookFunc() DecodeHookFunc {
183+
return func(
184+
f reflect.Type,
185+
t reflect.Type,
186+
data interface{},
187+
) (interface{}, error) {
188+
if f.Kind() != reflect.String {
189+
return data, nil
190+
}
191+
if t != reflect.TypeOf(&url.URL{}) {
192+
return data, nil
193+
}
194+
195+
// Convert it by parsing
196+
return url.Parse(data.(string))
197+
}
198+
}
199+
179200
// StringToIPHookFunc returns a DecodeHookFunc that converts
180201
// strings to net.IP
181202
func StringToIPHookFunc() DecodeHookFunc {

decode_hooks_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"math/big"
77
"net"
88
"net/netip"
9+
"net/url"
910
"reflect"
1011
"strings"
1112
"testing"
@@ -286,6 +287,35 @@ func TestStringToTimeDurationHookFunc(t *testing.T) {
286287
}
287288
}
288289

290+
func TestStringToURLHookFunc(t *testing.T) {
291+
f := StringToURLHookFunc()
292+
293+
urlSample, _ := url.Parse("http://example.com")
294+
urlValue := reflect.ValueOf(urlSample)
295+
strValue := reflect.ValueOf("http://example.com")
296+
cases := []struct {
297+
f, t reflect.Value
298+
result interface{}
299+
err bool
300+
}{
301+
{reflect.ValueOf("http://example.com"), urlValue, urlSample, false},
302+
{reflect.ValueOf("http ://example.com"), urlValue, (*url.URL)(nil), true},
303+
{reflect.ValueOf("http://example.com"), strValue, "http://example.com", false},
304+
}
305+
306+
for i, tc := range cases {
307+
actual, err := DecodeHookExec(f, tc.f, tc.t)
308+
if tc.err != (err != nil) {
309+
t.Fatalf("case %d: expected err %#v", i, tc.err)
310+
}
311+
if !reflect.DeepEqual(actual, tc.result) {
312+
t.Fatalf(
313+
"case %d: expected %#v, got %#v",
314+
i, tc.result, actual)
315+
}
316+
}
317+
}
318+
289319
func TestStringToTimeHookFunc(t *testing.T) {
290320
strValue := reflect.ValueOf("5")
291321
timeValue := reflect.ValueOf(time.Time{})

0 commit comments

Comments
 (0)