-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsitemap_index.go
90 lines (78 loc) · 2.01 KB
/
sitemap_index.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package sitemap
import (
"encoding/xml"
"errors"
"fmt"
"time"
)
var ErrValidation = errors.New("validation error")
// xmlSitemapIndex is the XML representation of <sitemap>...</sitemap> used in sitemapindex
type xmlSitemapIndexItem struct {
Loc string `xml:"loc"`
LastMod string `xml:"lastmod"`
}
// xmlSitemapIndex is the XML representation of <sitemapindex>...</sitemapindex>
type xmlSitemapIndex struct {
XMLName xml.Name `xml:"sitemapindex"`
Sitemap []*xmlSitemapIndexItem `xml:"sitemap"`
Xmlns string `xml:"xmlns,attr"`
}
type Options struct {
PrettyOutput bool
WithXMLHeader bool
Validate bool
}
// SitemapIndex is the structure used to create new sitemap index
type SitemapIndex struct {
items []*SitemapIndexItem
options * Options
}
type SitemapIndexItem struct {
Loc string
LastMod time.Time
}
// NewSitemapIndex creates a new Sitemap Index
func NewSitemapIndex(items []*SitemapIndexItem, opts * Options) *SitemapIndex {
si := SitemapIndex{
items: items,
options: opts,
}
if si.options == nil {
si.options = NewOptions()
}
return &si
}
func (si * SitemapIndex) AddItem(loc string, lastMod time.Time) {
si.items = append(si.items, &SitemapIndexItem{Loc: loc, LastMod: lastMod})
}
func (si * SitemapIndex) RemoveItem(idx int) {
si.items = append(si.items[:idx], si.items[idx+1:]...)
}
func (si * SitemapIndex) ToXMLString() (string, error) {
itemsXML := make([]*xmlSitemapIndexItem, len(si.items))
for idx, i := range si.items {
if si.options.Validate && !isValidIndexItem(i) {
return "", ErrValidation
}
itemsXML[idx] = &xmlSitemapIndexItem {
Loc: i.Loc,
LastMod: formatTime(i.LastMod),
}
}
siXML := xmlSitemapIndex{
Sitemap: itemsXML,
Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
}
result, err := xmlMarshal(si.options, siXML)
if err != nil {
return "", err
}
return result, nil
}
func isValidIndexItem(i * SitemapIndexItem) bool {
if !validateURL(i.Loc) {
_ = fmt.Errorf("[validation error] Invalid URL: %s\n", i.Loc)
return false
}
return true
}