生成sitemap.xml示范demo

package services

import (
    "encoding/xml"
    "fmt"
    "log"
    "os"
    "github.com/gin-gonic/gin"
    "time"
    model "btcinfo/models"
    "context"
    "math" //向上取整需要
    "go.mongodb.org/mongo-driver/bson"

)

// URL 结构体定义了 sitemap.xml 文件中的每个 URL 条目
type URL struct {
    XMLName   xml.Name `xml:"url"`
    Loc       string   `xml:"loc"`
    LastMod   string   `xml:"lastmod,omitempty"`
    ChangeFreq string   `xml:"changefreq,omitempty"`
    Priority  float64  `xml:"priority,omitempty"`
}

// Sitemap 结构体定义了 sitemap.xml 文件的根元素
type Sitemap struct {
    XMLName xml.Name `xml:"urlset"`
    Xmlns   string   `xml:"xmlns,attr"`
    URLs    []URL    `xml:"url"`
}





//创建函数
func UpSitemap(c *gin.Context) {
    var Urls []URL
    log.Print("sitemap运行")

    //遍历语言代码并追加
    for _, lang := range Langs {
        //首页
        index := URL{
            Loc:       "https://info.com/"+lang,
            LastMod:   "2024-03-28",
            ChangeFreq: "yearly",
            Priority: 0.6,
        }
        Urls = append(Urls, index) //追加

        //列表faq
        //查询条件
        filter := bson.D{{Key: "dalei", Value: "faq"},{Key: "lang", Value: lang}}
        //取当前条件的总条数
        zongtiaoshu, _ := model.FaqModel.CountDocuments(context.TODO(), filter)
        //根据总条数计算总页数
        zongyeshu := int64(math.Ceil(float64(zongtiaoshu) / 12))
        log.Print("faq总页数",zongyeshu)
        //循环
        for i := int64(0); i < zongyeshu; i++ {
            log.Print("循环",i+1)
            lists1 := URL{
                Loc:       "https://info.com/"+lang+"/lists/faq/" +fmt.Sprint((i+1)),
                LastMod:   "2024-03-28",
                ChangeFreq: "weekly",
                Priority: 0.3,
            }
            Urls = append(Urls, lists1) //追加
        }

        //文章列表
        //查询条件
        filter = bson.D{{Key: "dalei", Value: "article"},{Key: "lang", Value: lang}}
        //取当前条件的总条数
        zongtiaoshu, _ = model.ArticleModel.CountDocuments(context.TODO(), filter)
        //根据总条数计算总页数
        zongyeshu = int64(math.Ceil(float64(zongtiaoshu) / 12))
        log.Print("文章总页数",zongyeshu)
        //循环
        for i := int64(0); i < zongyeshu; i++ {
            log.Print("循环",i+1)
            lists1 := URL{
                Loc:       "https://info.com/"+lang+"/lists/article/" +fmt.Sprint((i+1)),
                LastMod:   "2024-03-28",
                ChangeFreq: "weekly",
                Priority: 0.3,
            }
            Urls = append(Urls, lists1) //追加
        }

        //文章faq
        //定义一个空的切片来存储查询结果
        var results []model.Article_modelcha
        //查询条件
        filter = bson.D{{Key: "lang", Value: lang}}
        // 执行查询操作
        cursor, err := model.FaqModel.Find(context.TODO(), filter)
        if err != nil {
            c.JSON(400, gin.H{"db_error": "FAQ表查询错误"})
            log.Print("faq表查询错误:", err)
            return
        }
        //将上面的查询结果转码赋值给变量&results
        if err = cursor.All(context.TODO(), &results); err != nil {
            // 处理解码错误
            c.JSON(500, gin.H{"db_error": err})
            log.Print("路由查询解码错误:", err)
            return
        }

        //遍历文章
        for _, r := range results {
            var date time.Time //判断是否存在更新时间
            if r.Update != (time.Time{}) {
                date = r.Update
            } else {
                date = r.CreatedAt
            }
            
            list := URL{
                Loc:       "https://info.com/" + lang + "/article/faq/" + r.ID.Hex(),
                LastMod:   date.Format("2006-01-02"),
                ChangeFreq: "monthly",
                Priority: 0.7,
            }
            Urls = append(Urls, list) //追加
            
        }


        //文章

        // 执行查询操作
        cursor, err = model.ArticleModel.Find(context.TODO(), filter)
        if err != nil {
            c.JSON(400, gin.H{"db_error": "FAQ表查询错误"})
            log.Print("faq表查询错误:", err)
            return
        }
        //将上面的查询结果转码赋值给变量&results
        if err = cursor.All(context.TODO(), &results); err != nil {
            // 处理解码错误
            c.JSON(500, gin.H{"db_error": err})
            log.Print("路由查询解码错误:", err)
            return
        }

        //遍历文章
        for _, r := range results {
            var date time.Time //判断是否存在更新时间
            if r.Update != (time.Time{}) {
                date = r.Update
            } else {
                date = r.CreatedAt
            }
            
            list := URL{
                Loc:       "https://info.com/" + lang + "/article/article/" + r.ID.Hex(),
                LastMod:   date.Format("2006-01-02"),
                ChangeFreq: "monthly",
                Priority: 0.8,
            }
            Urls = append(Urls, list) //追加
            
        }

    }

    // 创建一个新的 sitemap 结构体
    sitemap := Sitemap{
        Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
        URLs: Urls,
    }

    // 创建一个新的文件并打开以供写入
    file, err := os.Create("jingtai/sitemap.xml")
    if err != nil {
        log.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    // 使用 xml 包将 sitemap 结构体编码为 XML 格式,并写入到文件中
    encoder := xml.NewEncoder(file)
    encoder.Indent("", "  ")
    if err := encoder.Encode(sitemap); err != nil {
        log.Println("写入Sitemap.xml失败:", err)
        return
    }

    log.Println("Sitemap.xml更新完成!")
}