github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/types/urls.go (about) 1 // Copyright 2020 PingCAP, Inc. 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package types 15 16 import ( 17 "net" 18 "net/url" 19 "sort" 20 "strings" 21 22 "github.com/pingcap/errors" 23 cerror "github.com/pingcap/tiflow/pkg/errors" 24 ) 25 26 // URLs defines a slice of URLs as a type 27 type URLs []url.URL 28 29 // NewURLs return a URLs from a slice of formatted URL strings 30 func NewURLs(strs []string) (URLs, error) { 31 all := make([]url.URL, len(strs)) 32 if len(all) == 0 { 33 return nil, cerror.WrapError(cerror.ErrURLFormatInvalid, errors.New("no valid URLs given")) 34 } 35 for i, in := range strs { 36 in = strings.TrimSpace(in) 37 u, err := url.Parse(in) 38 if err != nil { 39 return nil, cerror.WrapError(cerror.ErrURLFormatInvalid, err) 40 } 41 if u.Scheme != "http" && u.Scheme != "https" && u.Scheme != "unix" && u.Scheme != "unixs" { 42 return nil, cerror.WrapError(cerror.ErrURLFormatInvalid, 43 errors.Errorf("URL scheme must be http, https, unix, or unixs: %s", in)) 44 } 45 if _, _, err := net.SplitHostPort(u.Host); err != nil { 46 return nil, cerror.WrapError(cerror.ErrURLFormatInvalid, 47 errors.Errorf(`URL address does not have the form "host:port": %s`, in)) 48 } 49 if u.Path != "" { 50 return nil, cerror.WrapError(cerror.ErrURLFormatInvalid, 51 errors.Errorf("URL must not contain a path: %s", in)) 52 } 53 all[i] = *u 54 } 55 us := URLs(all) 56 sort.Slice(us, func(i, j int) bool { return us[i].String() < us[j].String() }) 57 58 return us, nil 59 } 60 61 // String return a string of list of URLs witch separated by comma 62 func (us URLs) String() string { 63 return strings.Join(us.StringSlice(), ",") 64 } 65 66 // StringSlice return a slice of formatted string of URL 67 func (us URLs) StringSlice() []string { 68 out := make([]string, len(us)) 69 for i := range us { 70 out[i] = us[i].String() 71 } 72 73 return out 74 }