package ytid import ( "fmt" "regexp" ) var ( regexpYoutubeDomain = regexp.MustCompile(`youtu\.?be`) regexpURLPatterns = []*regexp.Regexp{ regexp.MustCompile(`youtu\.be\/([^#\&\?]{11})`), regexp.MustCompile(`\?v=([^#\&\?]{11})`), regexp.MustCompile(`\&v=([^#\&\?]{11})`), regexp.MustCompile(`embed\/([^#\&\?]{11})`), regexp.MustCompile(`\/v\/([^#\&\?]{11})`), } ) func GetID(url string) string { if !regexpYoutubeDomain.MatchString(url) { return "" } for _, pattern := range regexpURLPatterns { if pattern.MatchString(url) { return pattern.FindStringSubmatch(url)[1] } } return "" } func GetIDWithError(url string) (string, error) { if !regexpYoutubeDomain.MatchString(url) { return "", fmt.Errorf("ytid: not a youtube domain") } for _, pattern := range regexpURLPatterns { if pattern.MatchString(url) { return pattern.FindStringSubmatch(url)[1], nil } } return "", fmt.Errorf("ytid: no match found") } /* */