Last active
January 19, 2023 16:01
-
-
Save cp-sumi-k/73cc9607427876abbad92f2936123126 to your computer and use it in GitHub Desktop.
https://medium.com/canopas/automation-dynamic-sitemap-generation-with-golang-api-584f6c53ea9c - sitemap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sitemap | |
import ( | |
"encoding/xml" | |
"jobs" | |
"net/http" | |
"time" | |
"github.com/gin-gonic/gin" | |
) | |
type URL struct { | |
XMLName xml.Name `xml:"url"` | |
Loc string `xml:"loc"` | |
ChangeFreq string `xml:"changefreq"` | |
LastMod string `xml:"lastmod"` | |
Priority string `xml:"priority"` | |
} | |
type URLset struct { | |
XMLName xml.Name `xml:"urlset"` | |
XMLNS string `xml:"xmlns,attr"` | |
URL []URL `xml:"url"` | |
} | |
func (repository *SitemapRepository) GenerateSitemap(c *gin.Context) { | |
baseUrl := c.Query("baseUrl") | |
jobsUrl := baseUrl + '/jobs' | |
// Init all static urls for sitemap | |
sitemapUrls := []URL{ | |
{Loc: baseUrl, Priority: `1`}, | |
{Loc: jobsUrl, Priority: `1`}, | |
} | |
// Init all dynamic urls for sitemap | |
jobs, err := GetJobs() | |
for i := range jobs { | |
sitemapUrls = append(sitemapUrls, URL{Loc: jobsUrl + `/` + jobs[i].Id, Priority: `0.9`}) | |
} | |
// Add changefreq and lastmod to all urls | |
year, month, _ := time.Now().Date() //get current month and year | |
lastmod := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC).Format("2006-01-02T00:00:00.000Z") | |
for i := range sitemapUrls { | |
sitemapUrls[i].ChangeFreq = "monthly" | |
sitemapUrls[i].LastMod = lastmod | |
} | |
urlset := URLset{URL: sitemapUrls, XMLNS: "http://www.sitemaps.org/schemas/sitemap/0.9"} | |
c.Header("Content-Type", "application/xml") | |
c.XML(http.StatusOK, urlset) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment