-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsitemap.go
91 lines (81 loc) · 2.11 KB
/
sitemap.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
91
package sitemap
import (
"encoding/xml"
"fmt"
"time"
)
// xmlSitemap is the XML representation of <urlset>...</urlset> used in sitemap
type xmlSitemap struct {
XMLName xml.Name `xml:"urlset"`
URL []*xmlSitemapItem `xml:"url"`
Xmlns string `xml:"xmlns,attr"`
}
// xmlSitemapItem is the XML representation of <url> in <sitemap>
type xmlSitemapItem struct {
Loc string `xml:"loc"`
LastMod string `xml:"lastmod"`
ChangeFreq string `xml:"changefreq"`
Priority string `xml:"priority"`
}
// Sitemap is the structure used to create new sitemap
type Sitemap struct {
items []*SitemapItem
options * Options
}
type SitemapItem struct {
Loc string
LastMod time.Time
ChangeFreq string
Priority float32
}
func isValidItem(i * SitemapItem) bool {
if !validateURL(i.Loc) {
_ = fmt.Errorf("[validation error] Invalid URL: %s\n", i.Loc)
return false
}
if !validateChangeFreq(i.ChangeFreq) {
_ = fmt.Errorf("[validation error] Invalid ChangeFreq: %s\n", i.ChangeFreq)
return false
}
return true
}
// NewSitemap creates a new Sitemap
func NewSitemap(items []*SitemapItem, opts * Options) *Sitemap {
s := Sitemap{
items: items,
options: opts,
}
if s.options == nil {
s.options = NewOptions()
}
return &s
}
func (s * Sitemap) ToXMLString() (string, error) {
itemsXML := make([]*xmlSitemapItem, len(s.items))
for idx, i := range s.items {
if s.options.Validate && !isValidItem(i) {
return "", ErrValidation
}
itemsXML[idx] = &xmlSitemapItem {
Loc: i.Loc,
LastMod: formatTime(i.LastMod),
ChangeFreq: i.ChangeFreq,
Priority: fmt.Sprintf("%.1f", i.Priority),
}
}
siXML := xmlSitemap{
URL: itemsXML,
Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
}
result, err := xmlMarshal(s.options, siXML)
if err != nil {
return "", err
}
return result, nil
}
func (s * Sitemap) AddItem(loc string, lastMod time.Time, changeFreq string, priority float32) {
s.items = append(s.items, &SitemapItem{Loc: loc, LastMod: lastMod, ChangeFreq: changeFreq, Priority: priority})
}
func (s * Sitemap) RemoveItem(idx int) {
s.items = append(s.items[:idx], s.items[idx+1:]...)
}