xml.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package sitemap
  2. import (
  3. "context"
  4. "fmt"
  5. neturl "net/url"
  6. "path"
  7. "strings"
  8. )
  9. type EncodeToXmlInterface interface {
  10. EncodeToXml(ctx context.Context) string
  11. }
  12. func (s SiteMapBuilder) EncodeToXml(ctx context.Context) string {
  13. b := strings.Builder{}
  14. b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
  15. b.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
  16. var hostWithScheme string
  17. if h, ok := ctx.Value(hostWithSchemeKey).(string); ok {
  18. hostWithScheme = h
  19. }
  20. var urls = make([]URL, len(s.urls))
  21. copy(urls, s.urls)
  22. for _, contextfunc := range s.contextFuncs {
  23. urls = append(urls, contextfunc(ctx)...)
  24. }
  25. for _, model := range s.models {
  26. urls = append(urls, model.Sitemap(ctx)...)
  27. }
  28. for _, url := range urls {
  29. u, err := neturl.Parse(url.Loc)
  30. if err != nil {
  31. continue
  32. }
  33. if u.Host == "" {
  34. url.Loc = path.Join(hostWithScheme, url.Loc)
  35. }
  36. b.WriteString(`<url>`)
  37. b.WriteString(fmt.Sprintf(`<loc>%s</loc>`, url.Loc))
  38. if url.LastMod != "" {
  39. b.WriteString(fmt.Sprintf(`<lastmod>%s</lastmod>`, url.LastMod))
  40. }
  41. if url.Changefreq != "" {
  42. b.WriteString(fmt.Sprintf(`<changefreq>%s</changefreq>`, url.Changefreq))
  43. }
  44. if url.Priority != 0.0 {
  45. b.WriteString(fmt.Sprintf(`<priority>%f</priority>`, url.Priority))
  46. }
  47. b.WriteString(`</url>`)
  48. }
  49. b.WriteString(`</urlset>`)
  50. return b.String()
  51. }
  52. func (s SiteMapIndexBuilder) EncodeToXml(ctx context.Context) string {
  53. b := strings.Builder{}
  54. b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
  55. b.WriteString(`<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
  56. for _, site := range s.siteMaps {
  57. b.WriteString(`<sitemap>`)
  58. b.WriteString(fmt.Sprintf(`<loc>%s</loc>`, site.ToUrl(ctx)))
  59. b.WriteString(`</sitemap>`)
  60. }
  61. b.WriteString(`</sitemapindex>`)
  62. return b.String()
  63. }