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:
@@ -0,0 +1,137 @@
|
||||
// Package bing reads Bing Webmaster Tools through its API
|
||||
// (https://learn.microsoft.com/en-us/bingwebmaster/getting-access):
|
||||
// a site's traffic, its searches and its crawl issues. It only reads.
|
||||
package bing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const apiBase = "https://ssl.bing.com/webmaster/api.svc/json"
|
||||
|
||||
// ErrUnauthorized means the key was refused.
|
||||
var ErrUnauthorized = errors.New("Bing refused the API key")
|
||||
|
||||
// Client calls the API with one key.
|
||||
type Client struct {
|
||||
key, base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(key string) *Client {
|
||||
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: time.Minute}}
|
||||
}
|
||||
|
||||
// WithBase points the client at another server (for tests).
|
||||
func (c *Client) WithBase(u string) *Client {
|
||||
c.base = strings.TrimRight(u, "/")
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) get(ctx context.Context, method, site string, out any) error {
|
||||
q := url.Values{"apikey": {c.key}, "siteUrl": {site}}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/"+method+"?"+q.Encode(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, 16<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
var e struct {
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
if json.Unmarshal(raw, &e) == nil && e.Message != "" {
|
||||
return fmt.Errorf("Bing %s: %s", method, e.Message)
|
||||
}
|
||||
return fmt.Errorf("Bing %s: HTTP %d", method, res.StatusCode)
|
||||
}
|
||||
var env struct {
|
||||
D json.RawMessage `json:"d"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return fmt.Errorf("Bing %s: %w", method, err)
|
||||
}
|
||||
return json.Unmarshal(env.D, out)
|
||||
}
|
||||
|
||||
// Date is Bing's "/Date(1700000000000-0700)/".
|
||||
type Date struct{ time.Time }
|
||||
|
||||
var msDate = regexp.MustCompile(`/Date\((-?\d+)`)
|
||||
|
||||
func (d *Date) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return nil
|
||||
}
|
||||
if m := msDate.FindStringSubmatch(s); m != nil {
|
||||
ms, _ := strconv.ParseInt(m[1], 10, 64)
|
||||
d.Time = time.UnixMilli(ms).UTC()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Day is one day's (or week's) traffic.
|
||||
type Day struct {
|
||||
Date Date `json:"Date"`
|
||||
Clicks int `json:"Clicks"`
|
||||
Impressions int `json:"Impressions"`
|
||||
}
|
||||
|
||||
// Traffic is the site's clicks and impressions over time.
|
||||
func (c *Client) Traffic(ctx context.Context, site string) ([]Day, error) {
|
||||
var out []Day
|
||||
err := c.get(ctx, "GetRankAndTrafficStats", site, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Query is a search's numbers.
|
||||
type Query struct {
|
||||
Query string `json:"Query"`
|
||||
Date Date `json:"Date"`
|
||||
Clicks int `json:"Clicks"`
|
||||
Impressions int `json:"Impressions"`
|
||||
Position float64 `json:"AvgImpressionPosition"`
|
||||
}
|
||||
|
||||
// Queries are the site's searches, by week.
|
||||
func (c *Client) Queries(ctx context.Context, site string) ([]Query, error) {
|
||||
var out []Query
|
||||
err := c.get(ctx, "GetQueryStats", site, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// CrawlIssue is a page Bing had trouble with.
|
||||
type CrawlIssue struct {
|
||||
URL string `json:"Url"`
|
||||
HTTPCode int `json:"HttpCode"`
|
||||
Issues int `json:"Issues"` // flags
|
||||
InLinks int `json:"InLinks"`
|
||||
}
|
||||
|
||||
// CrawlIssues lists the pages Bing had trouble crawling.
|
||||
func (c *Client) CrawlIssues(ctx context.Context, site string) ([]CrawlIssue, error) {
|
||||
var out []CrawlIssue
|
||||
err := c.get(ctx, "GetCrawlIssues", site, &out)
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package bing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClient(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("apikey") != "k" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("siteUrl") != "https://us.example/" {
|
||||
t.Errorf("site: %s", r.URL)
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/GetRankAndTrafficStats":
|
||||
w.Write([]byte(`{"d":[{"__type":"x","Clicks":12,"Date":"/Date(1763337600000-0800)/","Impressions":340}]}`))
|
||||
case "/GetQueryStats":
|
||||
w.Write([]byte(`{"d":[{"Query":"nextcloud hosting","Clicks":2,"Impressions":90,"AvgImpressionPosition":8.5,"Date":"/Date(1763337600000)/"}]}`))
|
||||
case "/GetCrawlIssues":
|
||||
w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404,"Issues":1}]}`))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
ctx := context.Background()
|
||||
c := New("k").WithBase(srv.URL)
|
||||
days, err := c.Traffic(ctx, "https://us.example/")
|
||||
if err != nil || len(days) != 1 || days[0].Clicks != 12 || days[0].Date.Year() != 2025 {
|
||||
t.Errorf("traffic: %+v %v", days, err)
|
||||
}
|
||||
qs, err := c.Queries(ctx, "https://us.example/")
|
||||
if err != nil || qs[0].Position != 8.5 {
|
||||
t.Errorf("queries: %+v %v", qs, err)
|
||||
}
|
||||
is, err := c.CrawlIssues(ctx, "https://us.example/")
|
||||
if err != nil || is[0].HTTPCode != 404 {
|
||||
t.Errorf("issues: %+v %v", is, err)
|
||||
}
|
||||
if _, err := New("bad").WithBase(srv.URL).Traffic(ctx, "https://us.example/"); err != ErrUnauthorized {
|
||||
t.Errorf("bad key: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -154,3 +154,28 @@ func (c *Client) Analytics(ctx context.Context, site string, q Query) ([]Row, er
|
||||
q.StartRow += maxRows
|
||||
}
|
||||
}
|
||||
|
||||
// Sitemap is a sitemap Search Console knows about.
|
||||
type Sitemap struct {
|
||||
Path string `json:"path"`
|
||||
LastSubmitted *time.Time `json:"lastSubmitted"`
|
||||
LastDownloaded *time.Time `json:"lastDownloaded"`
|
||||
IsPending bool `json:"isPending"`
|
||||
Warnings string `json:"warnings"`
|
||||
Errors string `json:"errors"`
|
||||
Contents []struct {
|
||||
Type string `json:"type"`
|
||||
Submitted string `json:"submitted"`
|
||||
} `json:"contents"`
|
||||
}
|
||||
|
||||
// Sitemaps lists the sitemaps submitted for a property.
|
||||
func (c *Client) Sitemaps(ctx context.Context, site string) ([]Sitemap, error) {
|
||||
var out struct {
|
||||
Sitemap []Sitemap `json:"sitemap"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/sites/"+url.PathEscape(site)+"/sitemaps", nil, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out.Sitemap, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user