github.com/umeshredd/helm@v3.0.0-alpha.1+incompatible/pkg/urlutil/urlutil.go (about)

     1  /*
     2  Copyright The Helm Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package urlutil
    18  
    19  import (
    20  	"net/url"
    21  	"path"
    22  	"path/filepath"
    23  	"strings"
    24  )
    25  
    26  // URLJoin joins a base URL to one or more path components.
    27  //
    28  // It's like filepath.Join for URLs. If the baseURL is pathish, this will still
    29  // perform a join.
    30  //
    31  // If the URL is unparsable, this returns an error.
    32  func URLJoin(baseURL string, paths ...string) (string, error) {
    33  	u, err := url.Parse(baseURL)
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  	// We want path instead of filepath because path always uses /.
    38  	all := []string{u.Path}
    39  	all = append(all, paths...)
    40  	u.Path = path.Join(all...)
    41  	return u.String(), nil
    42  }
    43  
    44  // Equal normalizes two URLs and then compares for equality.
    45  func Equal(a, b string) bool {
    46  	au, err := url.Parse(a)
    47  	if err != nil {
    48  		a = filepath.Clean(a)
    49  		b = filepath.Clean(b)
    50  		// If urls are paths, return true only if they are an exact match
    51  		return a == b
    52  	}
    53  	bu, err := url.Parse(b)
    54  	if err != nil {
    55  		return false
    56  	}
    57  
    58  	for _, u := range []*url.URL{au, bu} {
    59  		if u.Path == "" {
    60  			u.Path = "/"
    61  		}
    62  		u.Path = filepath.Clean(u.Path)
    63  	}
    64  	return au.String() == bu.String()
    65  }
    66  
    67  // ExtractHostname returns hostname from URL
    68  func ExtractHostname(addr string) (string, error) {
    69  	u, err := url.Parse(addr)
    70  	if err != nil {
    71  		return "", err
    72  	}
    73  	return stripPort(u.Host), nil
    74  }
    75  
    76  // Backported from Go 1.8 because Circle is still on 1.7
    77  func stripPort(hostport string) string {
    78  	colon := strings.IndexByte(hostport, ':')
    79  	if colon == -1 {
    80  		return hostport
    81  	}
    82  	if i := strings.IndexByte(hostport, ']'); i != -1 {
    83  		return strings.TrimPrefix(hostport[:i], "[")
    84  	}
    85  	return hostport[:colon]
    86  
    87  }