mirror of
https://github.com/nkanaev/yarr.git
synced 2025-10-30 14:33:31 +00:00
youtube/vimeo iframes
This commit is contained in:
38
src/content/silo/iframe.go
Normal file
38
src/content/silo/iframe.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package silo
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
youtubeFrame = `<iframe src="https://www.youtube.com/embed/%s" width="560" height="315" frameborder="0" allowfullscreen></iframe>`
|
||||
vimeoFrame = `<iframe src="https://player.vimeo.com/video/%s" width="640" height="360" frameborder="0" allowfullscreen></iframe>`
|
||||
vimeoRegex = regexp.MustCompile(`\/(\d+)$`)
|
||||
)
|
||||
|
||||
func VideoIFrame(link string) string {
|
||||
l, err := url.Parse(link)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
youtubeID := ""
|
||||
if l.Host == "www.youtube.com" && l.Path == "/watch" {
|
||||
youtubeID = l.Query().Get("v")
|
||||
} else if l.Host == "youtu.be" {
|
||||
youtubeID = strings.TrimLeft(l.Path, "/")
|
||||
}
|
||||
if youtubeID != "" {
|
||||
return fmt.Sprintf(youtubeFrame, youtubeID)
|
||||
}
|
||||
|
||||
if l.Host == "vimeo.com" {
|
||||
if matches := vimeoRegex.FindStringSubmatch(l.Path); len(matches) > 0 {
|
||||
return fmt.Sprintf(vimeoFrame, matches[1])
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
36
src/content/silo/iframe_test.go
Normal file
36
src/content/silo/iframe_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package silo
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestYoutubeIframe(t *testing.T) {
|
||||
links := []string{
|
||||
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"https://youtu.be/dQw4w9WgXcQ",
|
||||
"https://youtu.be/dQw4w9WgXcQ",
|
||||
}
|
||||
for _, link := range links {
|
||||
have := VideoIFrame(link)
|
||||
want := `<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" width="560" height="315" frameborder="0" allowfullscreen></iframe>`
|
||||
if have != want {
|
||||
t.Logf("want: %s", want)
|
||||
t.Logf("have: %s", have)
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVimeoIframe(t *testing.T) {
|
||||
links := []string{
|
||||
"https://vimeo.com/channels/staffpicks/526381128",
|
||||
"https://vimeo.com/526381128",
|
||||
}
|
||||
for _, link := range links {
|
||||
have := VideoIFrame(link)
|
||||
want := `<iframe src="https://player.vimeo.com/video/526381128" width="640" height="360" frameborder="0" allowfullscreen></iframe>`
|
||||
if have != want {
|
||||
t.Logf("want: %s", want)
|
||||
t.Logf("have: %s", have)
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user