Phase 3 part 7: Bing, IndexNow and search engine setup

SEO → Search engines: a pull request that adds the IndexNow key file, a
robots.txt naming the sitemap, and turns the sitemap on when the Hugo
config disables it (checked with a build); IndexNow submissions of pages
that go live through Changes or Briefs once the key file is served; the
sitemaps Search Console has; and, with an API key, Bing's traffic,
searches and crawl issues. NewlyLive no longer queries while a result
set holds the database's only connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 08:45:13 -07:00
co-authored by Claude Opus 5.5
parent bf933971dd
commit 2302fb0436
18 changed files with 1061 additions and 4 deletions
+196
View File
@@ -0,0 +1,196 @@
package web
import (
"context"
"net/http"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/api/bing"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
)
var bingKey = secretField{"bing", secrets.BingAPIKey, "Bing Webmaster API key (optional)",
"In Bing Webmaster Tools: Settings (the gear) → API access → API key. Your site must be verified there.", "https://www.bing.com/webmasters"}
// bingBase is the Bing API's address; tests point it elsewhere.
var bingBase = ""
func (s *Server) bing() *bing.Client {
key := s.Secrets.Get(secrets.BingAPIKey)
if key == "" {
return nil
}
c := bing.New(key)
if bingBase != "" {
c.WithBase(bingBase)
}
return c
}
// bingSite is how Bing names a website: the profile's Bing site, or its
// address with a trailing slash.
func (s *Server) bingSite(site seoSite) string {
if p, _ := profile.Load(s.DB); p != nil && site.Index < len(p.Websites) && p.Websites[site.Index].BingSite != "" {
return p.Websites[site.Index].BingSite
}
return strings.TrimRight(site.URL, "/") + "/"
}
type bingQuery struct {
Query string
Clicks, Impressions int
Position float64
}
func (s *Server) seoEnginesPage(w http.ResponseWriter, r *http.Request) {
s.renderEngines(w, r, "")
}
func (s *Server) renderEngines(w http.ResponseWriter, r *http.Request, errMsg string) {
sites, cur := s.auditSites(r)
data := map[string]any{"Sites": sites, "Current": cur}
if cur != nil {
ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second)
defer cancel()
if c := s.gsc(); c != nil && cur.Property != "" {
maps, err := c.Sitemaps(ctx, cur.Property)
data["Sitemaps"], data["SitemapsErr"] = maps, errText(err)
}
data["GoogleConnected"] = s.gsc() != nil && cur.Property != ""
if b := s.bing(); b != nil {
site := s.bingSite(*cur)
data["BingSite"] = site
if days, err := b.Traffic(ctx, site); err != nil {
data["BingErr"] = err.Error()
} else {
slices.SortFunc(days, func(a, b bing.Day) int { return b.Date.Compare(a.Date.Time) })
if len(days) > 8 {
days = days[:8]
}
data["BingDays"] = days
if qs, err := b.Queries(ctx, site); err == nil {
data["BingQueries"] = topBingQueries(qs, 28)
}
if issues, err := b.CrawlIssues(ctx, site); err == nil {
data["BingIssues"] = issues
}
}
}
key, err := seo.IndexNowKey(s.DB)
if err != nil {
s.serverError(w, err)
return
}
f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO)")
data["Key"], data["KeyURL"], data["KeyLive"] = key, seo.KeyFileURL(cur.URL, key), seo.KeyLive(ctx, f, cur.URL, key)
data["Pings"] = seo.Pings(s.DB, cur.URL)
data["Setup"] = seo.LastSetup(s.DB, cur.URL)
data["Gitea"] = s.gitea() != nil
}
s.render(w, r, "seo-engines", page{Title: "Search engines", Nav: "seo/engines", Error: errMsg, Data: data})
}
func errText(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// topBingQueries sums the last weeks' rows per search, most impressions
// first.
func topBingQueries(qs []bing.Query, days int) []bingQuery {
since := time.Now().AddDate(0, 0, -days)
sum := map[string]*bingQuery{}
var pos = map[string]float64{}
for _, q := range qs {
if q.Date.Before(since) {
continue
}
b := sum[q.Query]
if b == nil {
b = &bingQuery{Query: q.Query}
sum[q.Query] = b
}
b.Clicks += q.Clicks
b.Impressions += q.Impressions
pos[q.Query] += q.Position * float64(q.Impressions)
}
var out []bingQuery
for k, b := range sum {
if b.Impressions > 0 {
b.Position = pos[k] / float64(b.Impressions)
}
out = append(out, *b)
}
slices.SortFunc(out, func(a, b bingQuery) int { return b.Impressions - a.Impressions })
if len(out) > 15 {
out = out[:15]
}
return out
}
// seoEnginesSetup opens the "set the site up for search engines" pull
// request.
func (s *Server) seoEnginesSetup(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
key, err := seo.IndexNowKey(s.DB)
if err == nil {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
_, err = s.applier(*cur).SetupSite(ctx, s.DB, cur.URL, key, time.Now())
}
if err != nil {
s.renderEngines(w, r, "Couldn't open the pull request: "+err.Error())
return
}
redirect(w, r, "/seo/engines?site="+strconv.Itoa(cur.Index), "setup-opened")
}
// seoEnginesPing submits the home page to IndexNow, to check it works.
func (s *Server) seoEnginesPing(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
key, err := seo.IndexNowKey(s.DB)
if err == nil {
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
_, err = seo.SubmitIndexNow(ctx, s.DB, cur.URL, key, []string{strings.TrimRight(cur.URL, "/") + "/"}, time.Now())
}
if err != nil {
s.renderEngines(w, r, "IndexNow: "+err.Error())
return
}
redirect(w, r, "/seo/engines?site="+strconv.Itoa(cur.Index), "pinged")
}
// pingNewlyLive submits pages that went live to IndexNow, once the site
// serves its key file.
func (s *Server) pingNewlyLive(ctx context.Context) {
key, err := seo.IndexNowKey(s.DB)
if err != nil {
return
}
f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO)")
for _, site := range s.seoSites() {
pages, err := seo.NewlyLive(s.DB, site.URL, time.Now())
if err != nil || len(pages) == 0 || !seo.KeyLive(ctx, f, site.URL, key) {
continue
}
if _, err := seo.SubmitIndexNow(ctx, s.DB, site.URL, key, pages, time.Now()); err != nil {
s.Log.Warn("seo: IndexNow", "site", site.URL, "err", err)
}
}
}
+60
View File
@@ -0,0 +1,60 @@
package web
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
)
func TestEnginesPage(t *testing.T) {
s, h := newTestServer(t, nil)
key, _ := seo.IndexNowKey(s.DB)
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/"+key+".txt" {
fmt.Fprint(w, key)
return
}
http.NotFound(w, r)
}))
defer site.Close()
b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/GetRankAndTrafficStats":
w.Write([]byte(`{"d":[{"Clicks":12,"Impressions":340,"Date":"/Date(1763337600000)/"}]}`))
case "/GetQueryStats":
w.Write([]byte(`{"d":[]}`))
case "/GetCrawlIssues":
w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404}]}`))
}
}))
defer b.Close()
bingBase = b.URL
defer func() { bingBase = "" }()
var pinged string
in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pinged = r.URL.Path; w.WriteHeader(200) }))
defer in.Close()
seo.IndexNowURL = in.URL
defer func() { seo.IndexNowURL = "https://api.indexnow.org/indexnow" }()
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: site.URL}}})
postForm(h, "/settings/search", url.Values{secrets.BingAPIKey: {"k"}})
body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String()
for _, want := range []string{key, "the site serves it", "340", "https://us.example/old (404)", "Connect Search Console", "Open the pull request"} {
if !strings.Contains(body, want) {
t.Errorf("page lacks %q", want)
}
}
if rec := postForm(h, "/seo/engines/ping?site=0", nil); rec.Code != http.StatusSeeOther || pinged == "" {
t.Errorf("ping: %d %q", rec.Code, pinged)
}
if body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String(); !strings.Contains(body, "accepted (200)") {
t.Error("the ping isn't listed")
}
}
+4 -1
View File
@@ -115,6 +115,8 @@ func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, er
"Fields": googleFields,
"Speed": pageSpeedKey,
"GiteaKey": giteaToken,
"BingKey": bingKey,
"BingSet": s.Secrets.Has(secrets.BingAPIKey),
"GiteaSet": s.Secrets.Has(secrets.GiteaToken),
"GiteaURL": s.giteaURL(),
"SpeedSet": s.Secrets.Has(secrets.PageSpeedAPIKey),
@@ -142,7 +144,7 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, append(googleFields, pageSpeedKey, giteaToken)); err != nil {
if err := s.saveSecrets(r, append(googleFields, pageSpeedKey, giteaToken, bingKey)); err != nil {
s.serverError(w, err)
return
}
@@ -268,6 +270,7 @@ func (s *Server) RunSEO(ctx context.Context) {
}
s.refreshChanges(ctx)
s.refreshBriefs(ctx)
s.pingNewlyLive(ctx)
select {
case <-ctx.Done():
return
+5
View File
@@ -161,6 +161,9 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
mux.HandleFunc("POST /seo/engines/setup", s.seoEnginesSetup)
mux.HandleFunc("POST /seo/engines/ping", s.seoEnginesPing)
mux.HandleFunc("GET /seo/briefs", s.seoBriefsPage)
mux.HandleFunc("POST /seo/briefs", s.seoBriefNew)
mux.HandleFunc("GET /seo/briefs/{id}", s.seoBriefPage)
@@ -425,6 +428,8 @@ var flashes = map[string]string{
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"report-written": "This week's report is written.",
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
"pinged": "Sent to IndexNow.",
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
"keywords-found": "Looked for keywords: the candidates are below.",
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+1
View File
@@ -47,6 +47,7 @@
<a href="/seo/keywords" {{if eq $nav "seo/keywords"}}aria-current="page"{{end}}>Next keywords</a>
<a href="/seo/briefs" {{if eq $nav "seo/briefs"}}aria-current="page"{{end}}>Briefs and pages</a>
<a href="/seo/audit" {{if eq $nav "seo/audit"}}aria-current="page"{{end}}>Audit</a>
<a href="/seo/engines" {{if eq $nav "seo/engines"}}aria-current="page"{{end}}>Search engines</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
@@ -34,6 +34,12 @@
</section>
{{end}}
<section class="card" id="bing">
<h3>Bing Webmaster Tools</h3>
<p class="small">Bing's clicks, impressions, searches and crawl issues, on SEO → Search engines. DuckDuckGo and many AI assistants draw on Bing's index.</p>
{{template "key-field" (dict "F" .BingKey "Set" .BingSet)}}
</section>
<section class="card" id="gitea">
<h3>Gitea: your sites' repositories</h3>
<p class="small">For changes you approve: Supermarket pushes a branch to the website's Hugo repository (set in the <a href="/settings/profile">profile</a>) and opens a pull request. It never merges.</p>
+60
View File
@@ -0,0 +1,60 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Search engines</h1></div>
<p class="lede">What Google and Bing know about the site, and IndexNow, which tells Bing and other engines the moment a page changes, so they don't wait for their next crawl. Google doesn't use IndexNow; it reads the sitemap.</p>
{{if not .Sites}}
<section class="card empty"><p>Add your websites to the <a href="/settings/profile">profile</a> first.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/seo/engines?site={{.Index}}" {{if eq .Index $d.Current.Index}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
<section class="card">
<h2>Set the site up for search engines</h2>
<p>One pull request that adds what's missing: the IndexNow key file, a <code>robots.txt</code> that names the sitemap (unless the site has its own), and the sitemap itself if the Hugo config turns it off. A Hugo build checks all three come out.</p>
{{with .Setup}}
{{if .Error}}<p class="error-text small">Last try, {{ago .At}}: {{.Error}}</p>
{{else}}<p class="small">Opened {{ago .At}}: <a href="{{.PRURL}}" target="_blank" rel="noopener noreferrer">pull request #{{.PRNumber}} ↗</a>. {{range .Done}}{{.}} {{end}}<br><span class="muted">{{.Note}}</span></p>{{end}}
{{end}}
<form method="post" action="/seo/engines/setup?site={{.Current.Index}}" data-busy="Opening…"><button type="submit" {{if not .Gitea}}disabled title="Save a Gitea token under Settings → Search engines"{{end}}>{{if .Setup}}Open it again{{else}}Open the pull request{{end}}</button></form>
</section>
<section class="card">
<h2>IndexNow</h2>
<p class="small">Key <code>{{.Key}}</code>, published at <a href="{{.KeyURL}}" target="_blank" rel="noopener noreferrer">{{.KeyURL}}</a>:
{{if .KeyLive}}<span class="ok">the site serves it.</span> Pages that go live through Changes or Briefs are submitted on their own.
{{else}}<span class="warn-text">not on the site yet.</span> Merge the setup pull request above; until then nothing is submitted.{{end}}</p>
{{if .KeyLive}}<form method="post" action="/seo/engines/ping?site={{.Current.Index}}" class="inline"><button type="submit" class="secondary small">Submit the home page now</button></form>{{end}}
{{if .Pings}}
<table class="list"><thead><tr><th>When</th><th>Pages</th><th>Result</th></tr></thead>
<tbody>{{range .Pings}}<tr><td>{{ago .At}}</td><td class="small">{{range .URLs}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">{{pagePath .}}</a> {{end}}</td>
<td class="small">{{if .Error}}<span class="error-text">{{.Error}}</span>{{else}}accepted ({{.Status}}){{end}}</td></tr>{{end}}</tbody></table>
{{end}}
</section>
<section class="card">
<h2>Google: sitemaps</h2>
{{if not .GoogleConnected}}<p class="help">Connect Search Console and choose this website's property under <a href="/settings/search">Settings → Search engines</a>.</p>
{{else if .SitemapsErr}}<p class="error-text">{{.SitemapsErr}}</p>
{{else if .Sitemaps}}
<table class="list"><thead><tr><th>Sitemap</th><th>Submitted</th><th>Last read</th><th>Pages</th><th>Problems</th></tr></thead>
<tbody>{{range .Sitemaps}}<tr><td class="small">{{.Path}}</td><td class="small">{{with .LastSubmitted}}{{ago .}}{{end}}</td><td class="small">{{with .LastDownloaded}}{{ago .}}{{else}}{{if .IsPending}}pending{{end}}{{end}}</td>
<td class="num">{{range .Contents}}{{if eq .Type "web"}}{{.Submitted}}{{end}}{{end}}</td><td class="small">{{if or (ne .Errors "0") (ne .Warnings "0")}}errors: {{.Errors}}, warnings: {{.Warnings}}{{else}}none{{end}}</td></tr>{{end}}</tbody></table>
{{else}}<p class="warn-text small">Google has no sitemap for this site. Once the site has one, submit it in Search Console (Indexing → Sitemaps): Supermarket's access is read-only.</p>{{end}}
</section>
<section class="card">
<h2>Bing</h2>
{{if not .BingSite}}<p class="help">Save a Bing Webmaster API key under <a href="/settings/search">Settings → Search engines</a> to see Bing's numbers.</p>
{{else if .BingErr}}<p class="error-text">{{.BingErr}} <span class="small muted">(site: {{.BingSite}})</span></p>
{{else}}
{{if .BingDays}}<table class="list"><thead><tr><th>Week of</th><th class="num">Clicks</th><th class="num">Impressions</th></tr></thead>
<tbody>{{range .BingDays}}<tr><td>{{.Date.Format "2 Jan 2006"}}</td><td class="num">{{num .Clicks}}</td><td class="num">{{num .Impressions}}</td></tr>{{end}}</tbody></table>
{{else}}<p class="help">No traffic data from Bing yet.</p>{{end}}
{{if .BingQueries}}<h3>Searches, last 4 weeks</h3>
<table class="list"><thead><tr><th>Search</th><th class="num">Impressions</th><th class="num">Clicks</th><th class="num">Position</th></tr></thead>
<tbody>{{range .BingQueries}}<tr><td>{{.Query}}</td><td class="num">{{num .Impressions}}</td><td class="num">{{num .Clicks}}</td><td class="num">{{dec1 .Position}}</td></tr>{{end}}</tbody></table>{{end}}
<h3>Crawl issues</h3>
{{if .BingIssues}}<ul class="small">{{range .BingIssues}}<li>{{.URL}}{{if .HTTPCode}} ({{.HTTPCode}}){{end}}</li>{{end}}</ul>{{else}}<p class="help">None.</p>{{end}}
{{end}}
</section>
{{end}}
{{end}}{{end}}