rewriter.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. // Rewriter modify item contents with a set of rewriting rules.
  35. func Rewriter(url, content string) string {
  36. for _, rewriteRule := range rewriteRules {
  37. content = rewriteRule(url, content)
  38. }
  39. return content
  40. }