github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/pkg/urlutil/urlutil.go (about)

     1  // Package urlutil provides helper function to check urls kind.
     2  // It supports http urls, git urls and transport url (tcp://, …)
     3  package urlutil
     4  
     5  import (
     6  	"regexp"
     7  	"strings"
     8  )
     9  
    10  var (
    11  	validPrefixes = map[string][]string{
    12  		"url":       {"http://", "https://"},
    13  		"git":       {"git://", "github.com/", "git@"},
    14  		"transport": {"tcp://", "tcp+tls://", "udp://", "unix://", "unixgram://"},
    15  	}
    16  	urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$")
    17  )
    18  
    19  // IsURL returns true if the provided str is an HTTP(S) URL.
    20  func IsURL(str string) bool {
    21  	return checkURL(str, "url")
    22  }
    23  
    24  // IsGitURL returns true if the provided str is a git repository URL.
    25  func IsGitURL(str string) bool {
    26  	if IsURL(str) && urlPathWithFragmentSuffix.MatchString(str) {
    27  		return true
    28  	}
    29  	return checkURL(str, "git")
    30  }
    31  
    32  // IsGitTransport returns true if the provided str is a git transport by inspecting
    33  // the prefix of the string for known protocols used in git.
    34  func IsGitTransport(str string) bool {
    35  	return IsURL(str) || strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@")
    36  }
    37  
    38  // IsTransportURL returns true if the provided str is a transport (tcp, tcp+tls, udp, unix) URL.
    39  func IsTransportURL(str string) bool {
    40  	return checkURL(str, "transport")
    41  }
    42  
    43  func checkURL(str, kind string) bool {
    44  	for _, prefix := range validPrefixes[kind] {
    45  		if strings.HasPrefix(str, prefix) {
    46  			return true
    47  		}
    48  	}
    49  	return false
    50  }