package handler import ( "encoding/xml" "fmt" "net/http" "time" "github.com/freefire/jiang13-bbs/model" "github.com/gin-gonic/gin" ) const siteBaseURL = "http://localhost:3000" // RobotsTxt robots.txt func (h *Handlers) RobotsTxt(c *gin.Context) { content := fmt.Sprintf(`User-agent: * Allow: / Sitemap: %s/sitemap.xml `, siteBaseURL) c.String(http.StatusOK, content) } // SitemapXML 生成 sitemap func (h *Handlers) SitemapXML(c *gin.Context) { type urlEntry struct { Loc string `xml:"loc"` Lastmod string `xml:"lastmod"` Changefreq string `xml:"changefreq"` Priority string `xml:"priority"` } type urlset struct { XMLName xml.Name `xml:"urlset"` Xmlns string `xml:"xmlns,attr"` URLs []urlEntry `xml:"url"` } now := time.Now().Format("2006-01-02") entries := []urlEntry{ {Loc: siteBaseURL + "/", Lastmod: now, Changefreq: "daily", Priority: "1.0"}, } // 板块页 var boards []model.Board model.DB.Find(&boards) for _, b := range boards { entries = append(entries, urlEntry{ Loc: fmt.Sprintf("%s/board/%d", siteBaseURL, b.ID), Lastmod: now, Changefreq: "daily", Priority: "0.8", }) } // 帖子详情页 var posts []model.Post model.DB.Where("status = ?", model.ContentStatusPublished). Order("created_at DESC").Limit(1000).Find(&posts) for _, p := range posts { entries = append(entries, urlEntry{ Loc: fmt.Sprintf("%s/post/%d", siteBaseURL, p.ID), Lastmod: p.UpdatedAt.Format("2006-01-02"), Changefreq: "weekly", Priority: "0.6", }) } us := urlset{ Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9", URLs: entries, } output, err := xml.MarshalIndent(us, "", " ") if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.Header("Content-Type", "application/xml") c.String(http.StatusOK, xml.Header+string(output)) }