Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Created August 31, 2025 18:36
Show Gist options
  • Select an option

  • Save wjkoh/8fb8e6a0cf52788c1b88102681767e5f to your computer and use it in GitHub Desktop.

Select an option

Save wjkoh/8fb8e6a0cf52788c1b88102681767e5f to your computer and use it in GitHub Desktop.
Go: How to Generate sitemap.xml
package main
import (
"encoding/xml"
"io"
)
const defaultXmlNs = "http://www.sitemaps.org/schemas/sitemap/0.9"
type Url struct {
Loc string `xml:"loc"`
}
type Sitemap struct {
XMLName xml.Name `xml:"urlset"`
XmlNs string `xml:"xmlns,attr"`
Url []*Url `xml:"url"`
}
func NewSitemap() *Sitemap {
return &Sitemap{XmlNs: defaultXmlNs}
}
func (s *Sitemap) AddUrl(u string) {
s.Url = append(s.Url, &Url{u})
}
func (s *Sitemap) Encode(w io.Writer) error {
_, err := w.Write([]byte(xml.Header))
if err != nil {
return err
}
return xml.NewEncoder(w).Encode(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment