rewriter.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package rewrite
  5. import (
  6. "regexp"
  7. "strings"
  8. "github.com/PuerkitoBio/goquery"
  9. )
  10. var rewriteRules = []func(string, string) string{
  11. func(url, content string) string {
  12. re := regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  13. matches := re.FindStringSubmatch(url)
  14. if len(matches) == 2 {
  15. video := `<iframe width="650" height="350" frameborder="0" src="https://www.youtube-nocookie.com/embed/` + matches[1] + `" allowfullscreen></iframe>`
  16. return video + "<p>" + content + "</p>"
  17. }
  18. return content
  19. },
  20. func(url, content string) string {
  21. if strings.HasPrefix(url, "https://xkcd.com") {
  22. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  23. if err != nil {
  24. return content
  25. }
  26. imgTag := doc.Find("img").First()
  27. if titleAttr, found := imgTag.Attr("title"); found {
  28. return content + `<blockquote cite="` + url + `">` + titleAttr + "</blockquote>"
  29. }
  30. }
  31. return content
  32. },
  33. }
  34. func Rewriter(url, content string) string {
  35. for _, rewriteRule := range rewriteRules {
  36. content = rewriteRule(url, content)
  37. }
  38. return content
  39. }