...

Source file src/go.etcd.io/etcd/client/pkg/v3/types/urls.go

Documentation: go.etcd.io/etcd/client/pkg/v3/types

     1  // Copyright 2015 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package types
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"net"
    21  	"net/url"
    22  	"sort"
    23  	"strings"
    24  )
    25  
    26  type URLs []url.URL
    27  
    28  func NewURLs(strs []string) (URLs, error) {
    29  	all := make([]url.URL, len(strs))
    30  	if len(all) == 0 {
    31  		return nil, errors.New("no valid URLs given")
    32  	}
    33  	for i, in := range strs {
    34  		in = strings.TrimSpace(in)
    35  		u, err := url.Parse(in)
    36  		if err != nil {
    37  			return nil, err
    38  		}
    39  
    40  		switch u.Scheme {
    41  		case "http", "https":
    42  			if _, _, err := net.SplitHostPort(u.Host); err != nil {
    43  				return nil, fmt.Errorf(`URL address does not have the form "host:port": %s`, in)
    44  			}
    45  
    46  			if u.Path != "" {
    47  				return nil, fmt.Errorf("URL must not contain a path: %s", in)
    48  			}
    49  		case "unix", "unixs":
    50  			break
    51  		default:
    52  			return nil, fmt.Errorf("URL scheme must be http, https, unix, or unixs: %s", in)
    53  		}
    54  		all[i] = *u
    55  	}
    56  	us := URLs(all)
    57  	us.Sort()
    58  	return us, nil
    59  }
    60  
    61  func MustNewURLs(strs []string) URLs {
    62  	urls, err := NewURLs(strs)
    63  	if err != nil {
    64  		panic(err)
    65  	}
    66  	return urls
    67  }
    68  
    69  func (us URLs) String() string {
    70  	return strings.Join(us.StringSlice(), ",")
    71  }
    72  
    73  func (us *URLs) Sort() {
    74  	sort.Sort(us)
    75  }
    76  func (us URLs) Len() int           { return len(us) }
    77  func (us URLs) Less(i, j int) bool { return us[i].String() < us[j].String() }
    78  func (us URLs) Swap(i, j int)      { us[i], us[j] = us[j], us[i] }
    79  
    80  func (us URLs) StringSlice() []string {
    81  	out := make([]string, len(us))
    82  	for i := range us {
    83  		out[i] = us[i].String()
    84  	}
    85  
    86  	return out
    87  }
    88  

View as plain text