Created
August 31, 2025 18:36
-
-
Save wjkoh/8fb8e6a0cf52788c1b88102681767e5f to your computer and use it in GitHub Desktop.
Go: How to Generate sitemap.xml
This file contains hidden or 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 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