-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsm.go
52 lines (45 loc) · 1.02 KB
/
gsm.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
package ginsitemap
import (
"bytes"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func New(path string) gin.HandlerFunc {
path = filepath.FromSlash(path)
if len(path) > 0 && !os.IsPathSeparator(path[0]) {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
path = filepath.Join(wd, path)
}
info, err := os.Stat(path)
if err != nil || info == nil || info.IsDir() {
panic("Invalid sitemap path: " + path)
}
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
reader := bytes.NewReader(file)
return func(c *gin.Context) {
if c.Request.RequestURI != "/sitemap.xml" {
return
}
if c.Request.Method != "GET" && c.Request.Method != "HEAD" {
status := http.StatusOK
if c.Request.Method != "OPTIONS" {
status = http.StatusMethodNotAllowed
}
c.Header("Allow", "GET,HEAD,OPTIONS")
c.AbortWithStatus(status)
return
}
c.Header("Content-Type", "text/xml")
http.ServeContent(c.Writer, c.Request, "sitemap.xml", info.ModTime(), reader)
return
}
}