-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex_sitemap.go
executable file
·117 lines (98 loc) · 2.55 KB
/
index_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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package gositemap
import (
"bytes"
"encoding/xml"
"path/filepath"
)
//IndexSitemapOpt option for sitemap
type IndexSitemapOpt func(*IndexSitemap)
//IndexSitemap index sitemap entity representation
type IndexSitemap struct {
fileName string
dir string
content []byte
publicPath string
host string
countSitemaps int
compress bool
}
//SitemapEntity sitemap item representation
type SitemapEntity struct {
XMLName xml.Name `xml:"sitemap"`
Loc string `xml:"loc"`
LastMod XMLTime `xml:"lastmod,omitempty"`
}
//NewIndexSitemap creates new index sitemap
func NewIndexSitemap(opts ...IndexSitemapOpt) *IndexSitemap {
s := &IndexSitemap{
fileName: "sitemap.xml",
dir: "./",
content: make([]byte, 0, 256),
host: "https://example.com",
}
for _, opt := range opts {
opt(s)
}
return s
}
//Add new sitemap entity in index sitemap
func (s *IndexSitemap) Add(e *SitemapEntity) error {
e.Loc = s.host + "/" + s.publicPath + e.Loc
b, err := xml.Marshal(e)
if err != nil {
return err
}
if s.validate(append(s.content, b...)) && s.countSitemaps+1 <= maxUrls {
s.content = append(s.content, b...)
s.countSitemaps++
return nil
}
return ErrorAddEntity
}
func (s *IndexSitemap) validate(content []byte) bool {
return len(content)+len(indexSitemapXMLHeader)+len(indexSitemapXMLFooter) < maxFileSize
}
//Build index sitemap
func (s *IndexSitemap) Build() error {
fullPath := filepath.Join(
s.dir,
s.fileName,
)
return writeFile(s.dir, fullPath, s.GetXML(), s.compress)
}
//GetXML return xml output
func (s *IndexSitemap) GetXML() []byte {
c := bytes.Join(bytes.Fields(indexSitemapXMLHeader), []byte(" "))
c = append(append(c, s.content...), indexSitemapXMLFooter...)
return c
}
//DirIndexOpt set dir for index sitemap
func DirIndexOpt(dir string) IndexSitemapOpt {
return func(sitemap *IndexSitemap) {
sitemap.dir = dir
}
}
//FileNameIndexOpt set filename for index sitemap
func FileNameIndexOpt(fileName string) IndexSitemapOpt {
return func(sitemap *IndexSitemap) {
sitemap.fileName = fileName
}
}
//HostIndexOpt set host for index sitemap
func HostIndexOpt(host string) IndexSitemapOpt {
return func(sitemap *IndexSitemap) {
sitemap.host = host
}
}
//CompressIndexOpt compress to .gz for sitemap
func CompressIndexOpt(compress bool) IndexSitemapOpt {
return func(sitemap *IndexSitemap) {
sitemap.compress = compress
}
}
//PublicPathIndexOpt set public path in sitemap
func PublicPathIndexOpt(path string) IndexSitemapOpt {
return func(sitemap *IndexSitemap) {
sitemap.publicPath = path
}
}