Browse Source

Merge f82536fea2 into 1ffadf5510

pull/83/merge
andrewheberle GitHub 4 years ago
parent
commit
74802afa3b
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 1 deletions
  1. +10
    -1
      cast.go
  2. +30
    -0
      cast_test.go
  3. +15
    -0
      caste.go

+ 10
- 1
cast.go View File

@@ -6,7 +6,10 @@
// Package cast provides easy and safe casting in Go.
package cast

import "time"
import (
"net/url"
"time"
)

// ToBool casts an interface to a bool type.
func ToBool(i interface{}) bool {
@@ -20,6 +23,12 @@ func ToTime(i interface{}) time.Time {
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.
func ToDuration(i interface{}) time.Duration {
v, _ := ToDurationE(i)


+ 30
- 0
cast_test.go View File

@@ -8,6 +8,8 @@ package cast
import (
"fmt"
"html/template"
"net/url"
"reflect"
"testing"
"time"

@@ -1285,3 +1287,31 @@ func TestToDurationE(t *testing.T) {
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)
}
})
}
}

+ 15
- 0
caste.go View File

@@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"html/template"
"net/url"
"reflect"
"strconv"
"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.
func ToBoolE(i interface{}) (bool, error) {
i = indirect(i)


Loading…
Cancel
Save