-
Notifications
You must be signed in to change notification settings - Fork 26
/
indexnow.go
89 lines (81 loc) · 1.94 KB
/
indexnow.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
package main
import (
"context"
"net/http"
"github.com/carlmjohnson/requests"
)
// Implement support for the IndexNow protocol
// https://www.indexnow.org/documentation
func (a *goBlog) initIndexNow() {
if !a.indexNowEnabled() {
return
}
// Add hooks
hook := func(p *post) {
// Check if post is published
if !p.isPublicPublishedSectionPost() {
return
}
// Send IndexNow request
a.indexNow(a.fullPostURL(p))
}
a.pPostHooks = append(a.pPostHooks, hook)
a.pUpdateHooks = append(a.pUpdateHooks, hook)
}
func (a *goBlog) indexNowEnabled() bool {
// Check if private mode is enabled
if a.isPrivate() {
return false
}
// Check if IndexNow is disabled
if inc := a.cfg.IndexNow; inc == nil || !inc.Enabled {
return false
}
return true
}
func (a *goBlog) serveIndexNow(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(a.indexNowKey())
}
func (a *goBlog) indexNow(url string) {
if !a.indexNowEnabled() {
return
}
key := a.indexNowKey()
if len(key) == 0 {
a.info("Skipping IndexNow")
return
}
err := requests.URL("https://api.indexnow.org/indexnow").
Client(a.httpClient).
Param("url", url).
Param("key", string(key)).
Fetch(context.Background())
if err != nil {
a.error("Sending IndexNow request failed", "err", err)
return
} else {
a.info("IndexNow request sent", "url", url)
}
}
func (a *goBlog) indexNowKey() []byte {
a.inLoad.Do(func() {
// Try to load key from database
keyBytes, err := a.db.retrievePersistentCache("indexnowkey")
if err != nil {
a.error("Failed to retrieve cached IndexNow key", "err", err)
return
}
if keyBytes == nil {
// Generate 128 character key with hexadecimal characters
keyBytes = []byte(randomString(128, []rune("0123456789abcdef")...))
// Store key in database
err = a.db.cachePersistently("indexnowkey", keyBytes)
if err != nil {
a.error("Failed to cache IndexNow key", "err", err)
return
}
}
a.inKey = keyBytes
})
return a.inKey
}