// Package gsc reads Google Search Console (the Search Console API v3, // https://developers.google.com/webmaster-tools/v1/api_reference_index): // the properties the signed-in account can see, and their search // analytics. It only reads. package gsc import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" ) const apiBase = "https://www.googleapis.com/webmasters/v3" // ErrUnauthorized means Google refused the token: sign in again. var ErrUnauthorized = errors.New("Google refused the sign-in: connect Search Console again") // TokenFunc returns a current access token. type TokenFunc func(ctx context.Context) (string, error) // Client calls the API with tokens from a TokenFunc. type Client struct { token TokenFunc base string http *http.Client } func New(token TokenFunc) *Client { return &Client{token: token, base: apiBase, http: &http.Client{Timeout: 2 * 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) do(ctx context.Context, method, path string, body, out any) error { tok, err := c.token(ctx) if err != nil { return err } var rd io.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { return err } rd = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, c.base+path, rd) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+tok) if body != nil { req.Header.Set("Content-Type", "application/json") } res, err := c.http.Do(req) if err != nil { return err } defer res.Body.Close() raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<20)) if err != nil { return err } if res.StatusCode == http.StatusUnauthorized { return ErrUnauthorized } if res.StatusCode != http.StatusOK { var e struct { Error struct { Message string `json:"message"` } `json:"error"` } if json.Unmarshal(raw, &e) == nil && e.Error.Message != "" { return fmt.Errorf("Search Console: %s", e.Error.Message) } return fmt.Errorf("Search Console: HTTP %d", res.StatusCode) } return json.Unmarshal(raw, out) } // Site is a property the account can read. type Site struct { URL string `json:"siteUrl"` // "sc-domain:example.com" or "https://example.com/" Permission string `json:"permissionLevel"` } // Sites lists the properties the account can see. func (c *Client) Sites(ctx context.Context) ([]Site, error) { var out struct { Entries []Site `json:"siteEntry"` } if err := c.do(ctx, http.MethodGet, "/sites", nil, &out); err != nil { return nil, err } var usable []Site for _, s := range out.Entries { if s.Permission != "siteUnverifiedUser" { usable = append(usable, s) } } return usable, nil } // Query is a Search Analytics query. type Query struct { StartDate string `json:"startDate"` // YYYY-MM-DD EndDate string `json:"endDate"` Dimensions []string `json:"dimensions,omitempty"` // date, page, query, country, device Type string `json:"type,omitempty"` // web (default) RowLimit int `json:"rowLimit,omitempty"` // up to 25000 StartRow int `json:"startRow,omitempty"` DataState string `json:"dataState,omitempty"` // final (default) or all } // Row is one result: the dimensions' values in order, and the numbers. type Row struct { Keys []string `json:"keys"` Clicks float64 `json:"clicks"` Impressions float64 `json:"impressions"` CTR float64 `json:"ctr"` Position float64 `json:"position"` } // maxRows is Google's page size. const maxRows = 25000 // Analytics runs a query, reading every page of rows. func (c *Client) Analytics(ctx context.Context, site string, q Query) ([]Row, error) { path := "/sites/" + url.PathEscape(site) + "/searchAnalytics/query" q.RowLimit = maxRows var all []Row for { var out struct { Rows []Row `json:"rows"` } if err := c.do(ctx, http.MethodPost, path, q, &out); err != nil { return nil, err } all = append(all, out.Rows...) if len(out.Rows) < maxRows { return all, nil } 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 }