github.com/kruglovmax/helm@v3.0.0-beta.3+incompatible/internal/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  )
    24  
    25  // URLJoin joins a base URL to one or more path components.
    26  //
    27  // It's like filepath.Join for URLs. If the baseURL is pathish, this will still
    28  // perform a join.
    29  //
    30  // If the URL is unparsable, this returns an error.
    31  func URLJoin(baseURL string, paths ...string) (string, error) {
    32  	u, err := url.Parse(baseURL)
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  	// We want path instead of filepath because path always uses /.
    37  	all := []string{u.Path}
    38  	all = append(all, paths...)
    39  	u.Path = path.Join(all...)
    40  	return u.String(), nil
    41  }
    42  
    43  // Equal normalizes two URLs and then compares for equality.
    44  func Equal(a, b string) bool {
    45  	au, err := url.Parse(a)
    46  	if err != nil {
    47  		a = filepath.Clean(a)
    48  		b = filepath.Clean(b)
    49  		// If urls are paths, return true only if they are an exact match
    50  		return a == b
    51  	}
    52  	bu, err := url.Parse(b)
    53  	if err != nil {
    54  		return false
    55  	}
    56  
    57  	for _, u := range []*url.URL{au, bu} {
    58  		if u.Path == "" {
    59  			u.Path = "/"
    60  		}
    61  		u.Path = filepath.Clean(u.Path)
    62  	}
    63  	return au.String() == bu.String()
    64  }
    65  
    66  // ExtractHostname returns hostname from URL
    67  func ExtractHostname(addr string) (string, error) {
    68  	u, err := url.Parse(addr)
    69  	if err != nil {
    70  		return "", err
    71  	}
    72  	return u.Hostname(), nil
    73  }