This commit is contained in:
andrewheberle 2020-02-01 01:04:10 +03:00 committed by GitHub
commit 74802afa3b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 1 deletions

11
cast.go
View File

@ -6,7 +6,10 @@
// Package cast provides easy and safe casting in Go. // Package cast provides easy and safe casting in Go.
package cast package cast
import "time" import (
"net/url"
"time"
)
// ToBool casts an interface to a bool type. // ToBool casts an interface to a bool type.
func ToBool(i interface{}) bool { func ToBool(i interface{}) bool {
@ -20,6 +23,12 @@ func ToTime(i interface{}) time.Time {
return v return v
} }
// ToURL casts an interface to a *url.URL type.
func ToURL(i interface{}) *url.URL {
v, _ := ToURLE(i)
return v
}
// ToDuration casts an interface to a time.Duration type. // ToDuration casts an interface to a time.Duration type.
func ToDuration(i interface{}) time.Duration { func ToDuration(i interface{}) time.Duration {
v, _ := ToDurationE(i) v, _ := ToDurationE(i)

View File

@ -8,6 +8,8 @@ package cast
import ( import (
"fmt" "fmt"
"html/template" "html/template"
"net/url"
"reflect"
"testing" "testing"
"time" "time"
@ -1285,3 +1287,31 @@ func TestToDurationE(t *testing.T) {
assert.Equal(t, test.expect, v, errmsg) assert.Equal(t, test.expect, v, errmsg)
} }
} }
func TestToURLE(t *testing.T) {
type args struct {
i interface{}
}
tests := []struct {
name string
args args
wantU *url.URL
wantErr bool
}{
{"url", args{&url.URL{Scheme: "https", Host: "example.net", Path: "/"}}, &url.URL{Scheme: "https", Host: "example.net", Path: "/"}, false},
{"string", args{string("https://example.net/")}, &url.URL{Scheme: "https", Host: "example.net", Path: "/"}, false},
{"invalid", args{int(100)}, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotU, err := ToURLE(tt.args.i)
if (err != nil) != tt.wantErr {
t.Errorf("ToURLE() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotU, tt.wantU) {
t.Errorf("ToURLE() = %v, want %v", gotU, tt.wantU)
}
})
}
}

View File

@ -10,6 +10,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"html/template" "html/template"
"net/url"
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
@ -70,6 +71,20 @@ func ToDurationE(i interface{}) (d time.Duration, err error) {
} }
} }
// ToURLE casts an interface to a *url.URL type.
func ToURLE(i interface{}) (u *url.URL, err error) {
i = indirect(i)
switch v := i.(type) {
case url.URL:
return &v, nil
case string:
return url.Parse(v)
default:
return nil, fmt.Errorf("unable to cast %#v of type %T to URL", i, i)
}
}
// ToBoolE casts an interface to a bool type. // ToBoolE casts an interface to a bool type.
func ToBoolE(i interface{}) (bool, error) { func ToBoolE(i interface{}) (bool, error) {
i = indirect(i) i = indirect(i)