This commit is contained in:
Darko Luketic 2019-07-01 15:47:29 +02:00
commit 48a3a6e79d
4 changed files with 85 additions and 0 deletions

9
LICENCE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2019 Darko Luketic
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

0
README.md Normal file
View File

45
ytid.go Normal file
View File

@ -0,0 +1,45 @@
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")
}
/*
*/

31
ytid_test.go Normal file
View File

@ -0,0 +1,31 @@
package ytid
import (
"testing"
)
func TestGetID(t *testing.T) {
inputs := []string{
"https://www.youtube.com/watch?v=m4U232MuTG4",
"https://youtu.be/dVtehSbLO8M",
"https://www.youtube.com/embed/Kt-tLuszKBA",
}
for n, i := range inputs {
switch n {
case 0:
if GetID(i) != "m4U232MuTG4" {
t.Fatal("failed", n)
}
case 1:
if GetID(i) != "dVtehSbLO8M" {
t.Fatal("failed", n)
}
case 2:
if GetID(i) != "Kt-tLuszKBA" {
t.Fatal("failed", n)
}
}
}
}