// Package bing reads Bing Webmaster Tools through its API // (https://learn.microsoft.com/en-us/bingwebmaster/getting-access): // a site's traffic, its searches, its crawl issues and the links to it. // 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, extra ...string) error { q := url.Values{"apikey": {c.key}, "siteUrl": {site}} for i := 0; i+1 < len(extra); i += 2 { q.Set(extra[i], extra[i+1]) } 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 } // LinkCount is how many links Bing knows to one page of the site. type LinkCount struct { URL string `json:"Url"` Count int `json:"Count"` } // LinkCounts are one page (from 0) of the site's pages with the number of // links to each, and how many pages of results there are. func (c *Client) LinkCounts(ctx context.Context, site string, page int) ([]LinkCount, int, error) { var out struct { Links []LinkCount `json:"Links"` TotalPages int `json:"TotalPages"` } err := c.get(ctx, "GetLinkCounts", site, &out, "page", strconv.Itoa(page)) return out.Links, out.TotalPages, err } // Link is a page that links to the site, with its anchor text. type Link struct { URL string `json:"Url"` Anchor string `json:"AnchorText"` } // URLLinks are one page (from 0) of the pages linking to one page of the // site, and how many pages of results there are. func (c *Client) URLLinks(ctx context.Context, site, target string, page int) ([]Link, int, error) { var out struct { Details []Link `json:"Details"` TotalPages int `json:"TotalPages"` } err := c.get(ctx, "GetUrlLinks", site, &out, "link", target, "page", strconv.Itoa(page)) return out.Details, out.TotalPages, err }