A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

95 lines
1.8 KiB

  1. package writefreely
  2. import (
  3. "fmt"
  4. "github.com/gorilla/mux"
  5. "github.com/ikeikeikeike/go-sitemap-generator/stm"
  6. "github.com/writeas/web-core/log"
  7. "net/http"
  8. "time"
  9. )
  10. func buildSitemap(host, alias string) *stm.Sitemap {
  11. sm := stm.NewSitemap()
  12. sm.SetDefaultHost(host)
  13. if alias != "/" {
  14. sm.SetSitemapsPath(alias)
  15. }
  16. sm.Create()
  17. // Note: Do not call `sm.Finalize()` because it flushes
  18. // the underlying datastructure from memory to disk.
  19. return sm
  20. }
  21. func handleViewSitemap(app *app, w http.ResponseWriter, r *http.Request) error {
  22. vars := mux.Vars(r)
  23. // Determine canonical blog URL
  24. alias := vars["collection"]
  25. subdomain := vars["subdomain"]
  26. isSubdomain := subdomain != ""
  27. if isSubdomain {
  28. alias = subdomain
  29. }
  30. host := fmt.Sprintf("%s/%s/", app.cfg.App.Host, alias)
  31. var c *Collection
  32. var err error
  33. pre := "/"
  34. if app.cfg.App.SingleUser {
  35. c, err = app.db.GetCollectionByID(1)
  36. } else {
  37. c, err = app.db.GetCollection(alias)
  38. }
  39. if err != nil {
  40. return err
  41. }
  42. if !isSubdomain {
  43. pre += alias + "/"
  44. }
  45. host = c.CanonicalURL()
  46. sm := buildSitemap(host, pre)
  47. posts, err := app.db.GetPosts(c, 0, false)
  48. if err != nil {
  49. log.Error("Error getting posts: %v", err)
  50. return err
  51. }
  52. lastSiteMod := time.Now()
  53. for i, p := range *posts {
  54. if i == 0 {
  55. lastSiteMod = p.Updated
  56. }
  57. u := stm.URL{
  58. "loc": p.Slug.String,
  59. "changefreq": "weekly",
  60. "mobile": true,
  61. "lastmod": p.Updated,
  62. }
  63. if len(p.Images) > 0 {
  64. imgs := []stm.URL{}
  65. for _, i := range p.Images {
  66. imgs = append(imgs, stm.URL{"loc": i, "title": ""})
  67. }
  68. u["image"] = imgs
  69. }
  70. sm.Add(u)
  71. }
  72. // Add top URL
  73. sm.Add(stm.URL{
  74. "loc": pre,
  75. "changefreq": "daily",
  76. "priority": "1.0",
  77. "lastmod": lastSiteMod,
  78. })
  79. w.Write(sm.XMLContent())
  80. return nil
  81. }