urlutil.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. import (
  5. "regexp"
  6. "strings"
  7. )
  8. var (
  9. validPrefixes = map[string][]string{
  10. "url": {"http://", "https://"},
  11. "git": {"git://", "github.com/", "git@"},
  12. "transport": {"tcp://", "tcp+tls://", "udp://", "unix://", "unixgram://"},
  13. }
  14. urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$")
  15. )
  16. // IsURL returns true if the provided str is an HTTP(S) URL.
  17. func IsURL(str string) bool {
  18. return checkURL(str, "url")
  19. }
  20. // IsGitURL returns true if the provided str is a git repository URL.
  21. func IsGitURL(str string) bool {
  22. if IsURL(str) && urlPathWithFragmentSuffix.MatchString(str) {
  23. return true
  24. }
  25. return checkURL(str, "git")
  26. }
  27. // IsGitTransport returns true if the provided str is a git transport by inspecting
  28. // the prefix of the string for known protocols used in git.
  29. func IsGitTransport(str string) bool {
  30. return IsURL(str) || strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@")
  31. }
  32. // IsTransportURL returns true if the provided str is a transport (tcp, tcp+tls, udp, unix) URL.
  33. func IsTransportURL(str string) bool {
  34. return checkURL(str, "transport")
  35. }
  36. func checkURL(str, kind string) bool {
  37. for _, prefix := range validPrefixes[kind] {
  38. if strings.HasPrefix(str, prefix) {
  39. return true
  40. }
  41. }
  42. return false
  43. }