git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/sitemap/sitemap.go (about) 1 package sitemap 2 3 import ( 4 "bytes" 5 "encoding/xml" 6 "io" 7 "time" 8 ) 9 10 // https://www.sitemaps.org/protocol.html 11 12 // ChangeFreq specifies change frequency of a sitemap entry. It is just a string. 13 type ChangeFreq string 14 15 const ( 16 Always ChangeFreq = "always" 17 Hourly ChangeFreq = "hourly" 18 Daily ChangeFreq = "daily" 19 Weekly ChangeFreq = "weekly" 20 Monthly ChangeFreq = "monthly" 21 Yearly ChangeFreq = "yearly" 22 Never ChangeFreq = "never" 23 ) 24 25 type Sitemap struct { 26 XMLName xml.Name `xml:"urlset"` 27 Xmlns string `xml:"xmlns,attr"` 28 Urls []URL `xml:"url"` 29 minify bool `xml:"-"` 30 } 31 32 type URL struct { 33 Loc string `xml:"loc"` 34 LastMod *time.Time `xml:"lastmod,omitempty"` 35 ChangeFreq ChangeFreq `xml:"changefreq,omitempty"` 36 Priority float32 `xml:"priority,omitempty"` 37 } 38 39 // New returns a new Sitemap. 40 func New(minify bool) *Sitemap { 41 return &Sitemap{ 42 Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9", 43 Urls: make([]URL, 0), 44 minify: minify, 45 } 46 } 47 48 // Add adds an URL to a Sitemap. 49 func (sitemap *Sitemap) Add(url URL) { 50 sitemap.Urls = append(sitemap.Urls, url) 51 } 52 53 // WriteTo writes XML encoded sitemap to given io.Writer. 54 // Implements io.WriterTo. 55 func (sitemap *Sitemap) WriteTo(w io.Writer) (err error) { 56 _, err = w.Write([]byte(xml.Header)) 57 if err != nil { 58 return 59 } 60 61 xmlEncoder := xml.NewEncoder(w) 62 if !sitemap.minify { 63 xmlEncoder.Indent("", " ") 64 } 65 66 err = xmlEncoder.Encode(sitemap) 67 w.Write([]byte{'\n'}) 68 return 69 } 70 71 func (sitemap *Sitemap) String() (ret string, err error) { 72 buffer := bytes.NewBufferString("") 73 74 err = sitemap.WriteTo(buffer) 75 if err != nil { 76 return 77 } 78 79 ret = buffer.String() 80 return 81 }