github.com/ngocphuongnb/tetua@v0.0.7-alpha/app/web/sitemap/post.go (about) 1 package websitemap 2 3 import ( 4 "encoding/xml" 5 "net/http" 6 "time" 7 8 "github.com/ngocphuongnb/tetua/app/entities" 9 "github.com/ngocphuongnb/tetua/app/repositories" 10 "github.com/ngocphuongnb/tetua/app/server" 11 ) 12 13 func Post(c server.Context) error { 14 currentPage := c.ParamInt("page", 1) 15 if currentPage < 1 { 16 return c.Status(http.StatusInternalServerError).SendString("Error") 17 } 18 19 posts, err := repositories.Post.Find(c.Context(), &entities.PostFilter{ 20 Filter: &entities.Filter{ 21 Page: currentPage, 22 Limit: SITEMAP_PAGESIZE, 23 Sorts: []*entities.Sort{{ 24 Field: "id", 25 Order: "ASC", 26 }}, 27 }, 28 }) 29 30 if err != nil { 31 c.Logger().Error(err) 32 return c.Status(http.StatusInternalServerError).SendString("Error") 33 } 34 35 sitemapPost := SitemapUrlSets{ 36 Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9", 37 XmlnsXsi: "http://www.w3.org/2001/XMLSchema-instance", 38 XmlnsImage: "http://www.google.com/schemas/sitemap-image/1.1", 39 XmlnsSchemaLocation: "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd", 40 } 41 42 for _, post := range posts { 43 sitemapUrl := &SitemapUrl{ 44 Loc: &SitemapLoc{ 45 Value: post.Url(), 46 }, 47 LastMod: &SitemapLastMod{ 48 Value: post.UpdatedAt.Format(time.RFC3339), 49 }, 50 } 51 52 if post.FeaturedImage != nil && post.FeaturedImage.Url() != "" { 53 sitemapUrl.Image = &SitemapImage{ 54 Loc: &SitemapImageLoc{ 55 Value: post.FeaturedImage.Url(), 56 }, 57 } 58 } 59 sitemapPost.Urls = append(sitemapPost.Urls, sitemapUrl) 60 } 61 62 sitemapBytes, err := xml.Marshal(sitemapPost) 63 64 if err != nil { 65 c.Logger().Error(err) 66 return c.Status(http.StatusInternalServerError).SendString("Error") 67 } 68 69 c.Response().Header("content-type", "text/xml; charset=UTF-8") 70 return c.SendString(`<?xml version="1.0" encoding="UTF-8"?>` + string(sitemapBytes)) 71 }