Browse Source

pkg/flags: support empty URLs string in NewURLsValue

Signed-off-by: Gyuho Lee <gyuhox@gmail.com>
Gyuho Lee 7 years ago
parent
commit
1e94968ffa
2 changed files with 32 additions and 16 deletions
  1. 10 6
      pkg/flags/urls.go
  2. 22 10
      pkg/flags/urls_test.go

+ 10 - 6
pkg/flags/urls.go

@@ -20,18 +20,17 @@ import (
 	"github.com/coreos/etcd/pkg/types"
 )
 
+// URLsValue wraps "types.URLs".
 type URLsValue types.URLs
 
 // Set parses a command line set of URLs formatted like:
 // http://127.0.0.1:2380,http://10.1.1.2:80
 func (us *URLsValue) Set(s string) error {
-	strs := strings.Split(s, ",")
-	nus, err := types.NewURLs(strs)
+	ss, err := types.NewURLs(strings.Split(s, ","))
 	if err != nil {
 		return err
 	}
-
-	*us = URLsValue(nus)
+	*us = URLsValue(ss)
 	return nil
 }
 
@@ -43,9 +42,14 @@ func (us *URLsValue) String() string {
 	return strings.Join(all, ",")
 }
 
-func NewURLsValue(init string) *URLsValue {
+// NewURLsValue implements "url.URL" slice as flag.Value interface.
+// Given value is to be separated by comma.
+func NewURLsValue(s string) *URLsValue {
+	if s == "" {
+		return &URLsValue{}
+	}
 	v := &URLsValue{}
-	if err := v.Set(init); err != nil {
+	if err := v.Set(s); err != nil {
 		plog.Panicf("new URLsValue should never fail: %v", err)
 	}
 	return v

+ 22 - 10
pkg/flags/urls_test.go

@@ -15,6 +15,8 @@
 package flags
 
 import (
+	"net/url"
+	"reflect"
 	"testing"
 )
 
@@ -45,17 +47,27 @@ func TestValidateURLsValueBad(t *testing.T) {
 	}
 }
 
-func TestValidateURLsValueGood(t *testing.T) {
-	tests := []string{
-		"https://1.2.3.4:8080",
-		"http://10.1.1.1:80",
-		"http://localhost:80",
-		"http://:80",
+func TestNewURLsValue(t *testing.T) {
+	tests := []struct {
+		s   string
+		exp []url.URL
+	}{
+		{s: "https://1.2.3.4:8080", exp: []url.URL{{Scheme: "https", Host: "1.2.3.4:8080"}}},
+		{s: "http://10.1.1.1:80", exp: []url.URL{{Scheme: "http", Host: "10.1.1.1:80"}}},
+		{s: "http://localhost:80", exp: []url.URL{{Scheme: "http", Host: "localhost:80"}}},
+		{s: "http://:80", exp: []url.URL{{Scheme: "http", Host: ":80"}}},
+		{
+			s: "http://localhost:1,https://localhost:2",
+			exp: []url.URL{
+				{Scheme: "http", Host: "localhost:1"},
+				{Scheme: "https", Host: "localhost:2"},
+			},
+		},
 	}
-	for i, in := range tests {
-		u := URLsValue{}
-		if err := u.Set(in); err != nil {
-			t.Errorf("#%d: err=%v, want nil for in=%q", i, err, in)
+	for i := range tests {
+		uu := []url.URL(*NewURLsValue(tests[i].s))
+		if !reflect.DeepEqual(tests[i].exp, uu) {
+			t.Fatalf("#%d: expected %+v, got %+v", i, tests[i].exp, uu)
 		}
 	}
 }