github.com/ngocphuongnb/tetua@v0.0.7-alpha/app/web/sitemap/sitemap.go (about)

     1  package websitemap
     2  
     3  import (
     4  	"encoding/xml"
     5  	"fmt"
     6  	"math"
     7  	"net/http"
     8  
     9  	"github.com/ngocphuongnb/tetua/app/repositories"
    10  	"github.com/ngocphuongnb/tetua/app/server"
    11  	"github.com/ngocphuongnb/tetua/app/utils"
    12  )
    13  
    14  func Index(c server.Context) error {
    15  
    16  	total, err := repositories.Post.Count(c.Context())
    17  
    18  	if err != nil {
    19  		c.Logger().Error(err)
    20  		return c.Status(http.StatusInternalServerError).SendString("Error")
    21  	}
    22  
    23  	totalPages := int(math.Ceil(float64(total) / float64(SITEMAP_PAGESIZE)))
    24  	sitemapIndex := SitemapItems{
    25  		Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
    26  	}
    27  
    28  	sitemapIndex.Items = []*SitemapItem{{
    29  		Loc: &SitemapLoc{
    30  			Value: utils.Url("/sitemap/topics.xml"),
    31  		},
    32  	}, {
    33  		Loc: &SitemapLoc{
    34  			Value: utils.Url("/sitemap/users.xml"),
    35  		},
    36  	}}
    37  
    38  	for i := 0; i < totalPages; i++ {
    39  		sitemapIndex.Items = append(sitemapIndex.Items, &SitemapItem{
    40  			Loc: &SitemapLoc{
    41  				Value: utils.Url(fmt.Sprintf("/sitemap/posts-%d.xml", i+1)),
    42  			},
    43  		})
    44  	}
    45  
    46  	sitemapBytes, err := xml.Marshal(sitemapIndex)
    47  
    48  	if err != nil {
    49  		c.Logger().Error(err)
    50  		return c.Status(http.StatusInternalServerError).SendString("Error")
    51  	}
    52  
    53  	c.Response().Header("content-type", "text/xml; charset=UTF-8")
    54  	return c.SendString(`<?xml version="1.0" encoding="UTF-8"?>` + string(sitemapBytes))
    55  }