GoBlog/indexnow.go

91 lines
2.0 KiB
Go
Raw Normal View History

2022-01-24 08:43:06 +00:00
package main
import (
"context"
"log"
"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
2022-12-26 18:52:06 +00:00
if !p.isPublicPublishedSectionPost() {
2022-01-24 08:43:06 +00:00
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
}
2022-02-26 19:38:52 +00:00
func (a *goBlog) serveIndexNow(w http.ResponseWriter, _ *http.Request) {
2022-02-25 15:29:42 +00:00
_, _ = w.Write(a.indexNowKey())
2022-01-24 08:43:06 +00:00
}
func (a *goBlog) indexNow(url string) {
if !a.indexNowEnabled() {
return
}
key := a.indexNowKey()
2022-02-25 15:29:42 +00:00
if len(key) == 0 {
2022-01-24 08:43:06 +00:00
log.Println("Skipping IndexNow")
return
}
err := requests.URL("https://api.indexnow.org/indexnow").
Client(a.httpClient).
Param("url", url).
2022-02-25 15:29:42 +00:00
Param("key", string(key)).
2022-01-24 08:43:06 +00:00
Fetch(context.Background())
if err != nil {
log.Println("Sending IndexNow request failed:", err.Error())
return
} else {
log.Println("IndexNow request sent for", url)
}
}
2022-02-25 15:29:42 +00:00
func (a *goBlog) indexNowKey() []byte {
a.inLoad.Do(func() {
2022-01-24 08:43:06 +00:00
// Try to load key from database
keyBytes, err := a.db.retrievePersistentCache("indexnowkey")
if err != nil {
log.Println("Failed to retrieve cached IndexNow key:", err.Error())
2022-02-25 15:29:42 +00:00
return
2022-01-24 08:43:06 +00:00
}
if keyBytes == nil {
// Generate 128 character key with hexadecimal characters
keyBytes = []byte(randomString(128, []rune("0123456789abcdef")...))
2022-01-24 08:43:06 +00:00
// Store key in database
err = a.db.cachePersistently("indexnowkey", keyBytes)
if err != nil {
log.Println("Failed to cache IndexNow key:", err.Error())
2022-02-25 15:29:42 +00:00
return
2022-01-24 08:43:06 +00:00
}
}
2022-02-25 15:29:42 +00:00
a.inKey = keyBytes
2022-01-24 08:43:06 +00:00
})
2022-02-25 15:29:42 +00:00
return a.inKey
2022-01-24 08:43:06 +00:00
}