github.com/oam-dev/kubevela@v1.9.11/pkg/utils/url.go (about) 1 /* 2 Copyright 2021 The KubeVela 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 utils 18 19 import ( 20 "fmt" 21 "net/url" 22 "path" 23 "regexp" 24 ) 25 26 // ParseAPIServerEndpoint automatically construct the full url of APIServer 27 // It will patch port and scheme if not exists 28 func ParseAPIServerEndpoint(server string) (string, error) { 29 r := regexp.MustCompile(`^((?P<scheme>http|https)://)?(?P<host>[^:\s]+)(:(?P<port>[0-9]+))?$`) 30 if !r.MatchString(server) { 31 return "", fmt.Errorf("invalid endpoint url: %s", server) 32 } 33 var scheme, port, host string 34 results := r.FindStringSubmatch(server) 35 for i, name := range r.SubexpNames() { 36 switch name { 37 case "scheme": 38 scheme = results[i] 39 case "host": 40 host = results[i] 41 case "port": 42 port = results[i] 43 } 44 } 45 if scheme == "" { 46 if port == "80" { 47 scheme = "http" 48 } else { 49 scheme = "https" 50 } 51 } 52 if port == "" { 53 if scheme == "http" { 54 port = "80" 55 } else { 56 port = "443" 57 } 58 } 59 return fmt.Sprintf("%s://%s:%s", scheme, host, port), nil 60 } 61 62 // IsValidURL checks whether the given string is a valid URL or not 63 func IsValidURL(strURL string) bool { 64 _, err := url.ParseRequestURI(strURL) 65 if err != nil { 66 return false 67 } 68 u, err := url.Parse(strURL) 69 if err != nil || u.Scheme == "" || u.Host == "" { 70 return false 71 } 72 return true 73 } 74 75 // JoinURL join baseURL and subPath to be new URL 76 func JoinURL(baseURL, subPath string) (string, error) { 77 parsedURL, err := url.Parse(baseURL) 78 if err != nil { 79 return "", err 80 } 81 parsedURL.RawPath = path.Join(parsedURL.RawPath, subPath) 82 parsedURL.Path = path.Join(parsedURL.Path, subPath) 83 URL := parsedURL.String() 84 return URL, nil 85 }