// 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 }