searchconsole

package
v0.0.0-...-bf55f72 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Provides programmatic access to reports and actions in Search Console.

Index

Constants

View Source
const (
	WebmastersScope     = "https://www.googleapis.com/auth/webmasters"          // Read/write access.
	WebmastersReadScope = "https://www.googleapis.com/auth/webmasters.readonly" // Read-only access.
)
View Source
const QueryURL = "https://www.googleapis.com/webmasters/v3/sites/%s/searchAnalytics/query"

Variables

View Source
var AllKnownPagesQueryParameters = &QueryParameters{
	StartDate:  "1970-01-01",
	EndDate:    time.Now().Format(time.DateOnly),
	Dimensions: []string{"page"},
	RowLimit:   25000,
}

AllKnownPagesQueryParameters used in SearchConsole.KnownPages to get a list of all known pages.

Functions

func AddSite

func AddSite(siteUrl string) error

AddSite uses SearchConsole.AddSite with DefaultSearchConsole.

func DefaultSearchConsoleFromJSONFile

func DefaultSearchConsoleFromJSONFile(name string) error

DefaultSearchConsoleFromJSONFile uses NewSearchConsoleFromJSONFile to set DefaultSearchConsole.

func DeleteSite

func DeleteSite(siteUrl string) error

DeleteSite uses SearchConsole.DeleteSite with DefaultSearchConsole.

func DeleteSitemap

func DeleteSitemap(siteUrl string, feedpath string) error

DeleteSitemap uses SearchConsole.DeleteSitemap with DefaultSearchConsole.

func KnownPages

func KnownPages(siteUrl string) ([]string, error)

KnownPages uses SearchConsole.KnownPages with DefaultSearchConsole.

func SubmitSitemap

func SubmitSitemap(siteUrl string, feedpath string) error

SubmitSitemap uses SearchConsole.SubmitSitemap with DefaultSearchConsole.

Types

type AmpInspectionResult

type AmpInspectionResult struct {
	Issues                []AmpIssue     `json:"issues" yaml:"Issues"`                               // A list of zero or more AMP issues found for the inspected URL.
	Verdict               Verdict        `json:"verdict" yaml:"Verdict"`                             // The status of the most severe error on the page. If a page has both warnings and errors, the page status is error. Error status means the page cannot be shown in Search results.
	AmpUrl                string         `json:"ampUrl" yaml:"AmpUrl"`                               // URL of the AMP that was inspected. If the submitted URL is a desktop page that refers to an AMP version, the AMP version will be inspected.
	RobotsTxtState        RobotsTxtState `json:"robotsTxtState" yaml:"RobotsTxtState"`               // Whether or not the page is blocked to Google by a robots.txt rule.
	IndexingState         IndexingState  `json:"indexingState" yaml:"IndexingState"`                 // Whether or not the page blocks indexing through a noindex rule.
	AmpIndexStatusVerdict Verdict        `json:"ampIndexStatusVerdict" yaml:"AmpIndexStatusVerdict"` // Index status of the AMP URL.
	LastCrawlTime         time.Time      `json:"lastCrawlTime" yaml:"LastCrawlTime"`                 // Last time this AMP version was crawled by Google. Absent if the URL was never crawled successfully.
	PageFetchState        PageFetchState `json:"pageFetchState" yaml:"PageFetchState"`               // Whether or not Google could fetch the AMP.
}

type AmpIssue

type AmpIssue struct {
	IssueMessage string `json:"issueMessage" yaml:"IssueMessage"` // Brief description of this issue.
	Severity     string `json:"severity" yaml:"Severity"`         // Severity of this issue: WARNING, or ERROR.
}

type CrawlingUserAgent

type CrawlingUserAgent string

The user agent type used for the crawl. Absent if your site was not crawled successfully.

const (
	CrawlingUserAgentUnspecified CrawlingUserAgent = "CRAWLING_USER_AGENT_UNSPECIFIED" // Unknown user agent.
	CrawlingUserAgentDesktop     CrawlingUserAgent = "DESKTOP"                         // Desktop user agent.
	CrawlingUserAgentMobile      CrawlingUserAgent = "MOBILE"                          // Mobile user agent.
)

type IndexStatusInspectionResult

type IndexStatusInspectionResult struct {
	Sitemap         []string          `json:"sitemap" yaml:"Sitemap"`                 // Any sitemaps that this URL was listed in, as known by Google. Not guaranteed to be an exhaustive list, especially if Google did not discover this URL through a sitemap. Absent if no sitemaps were found.
	ReferringUrls   []string          `json:"referringUrls" yaml:"ReferringUrls"`     // URLs that link to the inspected URL, directly and indirectly.
	Verdict         Verdict           `json:"verdict" yaml:"Verdict"`                 // High-level verdict about whether the URL is indexed.
	CoverageState   string            `json:"coverageState" yaml:"CoverageState"`     // Could Google find and index the page. More details about page indexing appear in 'indexingState'.
	RobotsTxtState  RobotsTxtState    `json:"robotsTxtState" yaml:"RobotsTxtState"`   // Whether or not the page is blocked to Google by a robots.txt rule.
	IndexingState   IndexingState     `json:"indexingState" yaml:"IndexingState"`     // Whether or not the page blocks indexing through a noindex rule.
	LastCrawlTime   time.Time         `json:"lastCrawlTime" yaml:"LastCrawlTime"`     // Last time this URL was crawled by Google using the primary crawler. Absent if the URL was never crawled successfully.
	PageFetchState  PageFetchState    `json:"pageFetchState" yaml:"GoogleCanonical"`  // Whether or not Google could retrieve the page from your server. Equivalent to "page fetch" in the URL inspection report.
	GoogleCanonical string            `json:"googleCanonical" yaml:"GoogleCanonical"` // The URL of the page that Google selected as canonical. If the page was not indexed, this field is absent.
	UserCanonical   string            `json:"userCanonical" yaml:"UserCanonical"`     // The URL that your page or site declares as canonical. If you did not declare a canonical URL, this field is absent.
	CrawledAs       CrawlingUserAgent `json:"crawledAs" yaml:"CrawledAs"`             // Primary crawler that was used by Google to crawl your site.
}

Results of index status inspection for either the live page or the version in Google's index, depending on whether you requested a live inspection or not. For more information, see the [Index coverage report documentation.](https://support.google.com/webmasters/answer/7440203)

type IndexingState

type IndexingState string
const (
	IndexingStateUnspecified         IndexingState = "INDEXING_STATE_UNSPECIFIED" // Unknown indexing status.
	IndexingStateAllowed             IndexingState = "INDEXING_ALLOWED"           // Indexing allowed.
	IndexingStateBlockedByMetaTag    IndexingState = "BLOCKED_BY_META_TAG"        // Indexing not allowed, 'noindex' detected in 'robots' meta tag.
	IndexingStateBlockedByHttpHeader IndexingState = "BLOCKED_BY_HTTP_HEADER"     // Indexing not allowed, 'noindex' detected in 'X-Robots-Tag' http header.
	IndexingStateBlockedByRobotsTxt  IndexingState = "BLOCKED_BY_ROBOTS_TXT"      // Reserved, no longer in use.
)

type PageFetchState

type PageFetchState string
const (
	PageFetchStateUnspecified        PageFetchState = "PAGE_FETCH_STATE_UNSPECIFIED" // Unknown fetch state.
	PageFetchStateSuccessful         PageFetchState = "SUCCESSFUL"                   // Successful fetch.
	PageFetchStateSoft404            PageFetchState = "SOFT_404"                     // Soft 404.
	PageFetchStateBlockedRobotsTxt   PageFetchState = "BLOCKED_ROBOTS_TXT"           // Blocked by robots.txt.
	PageFetchStateNotFound           PageFetchState = "NOT_FOUND"                    // Not found (404).
	PageFetchStateAccessDenied       PageFetchState = "ACCESS_DENIED"                // Blocked due to unauthorized request (401).
	PageFetchStateServerError        PageFetchState = "SERVER_ERROR"                 // Server error (5xx).
	PageFetchStateRedirectError      PageFetchState = "REDIRECT_ERROR"               // Redirection error.
	PageFetchStateAccessForbidden    PageFetchState = "ACCESS_FORBIDDEN"             // Blocked due to access forbidden (403).
	PageFetchStateBlocked4xx         PageFetchState = "BLOCKED_4XX"                  // Blocked due to other 4xx issue (not 403, 404).
	PageFetchStateInternalCrawlError PageFetchState = "INTERNAL_CRAWL_ERROR"         // Internal error.
	PageFetchStateInvalidUrl         PageFetchState = "INVALID_URL"                  // Invalid URL.
)

type QueryParameters

type QueryParameters struct {
	StartDate  string   `json:"startDate" yaml:"StartDate"`   // [Required] Start date of the requested date range, in YYYY-MM-DD format, in PT time (UTC - 7:00/8:00). Must be less than or equal to the end date. This value is included in the range.
	EndDate    string   `json:"endDate" yaml:"EndDate"`       // [Required] End date of the requested date range, in YYYY-MM-DD format, in PT time (UTC - 7:00/8:00). Must be greater than or equal to the start date. This value is included in the range.
	Dimensions []string `json:"dimensions" yaml:"Dimensions"` // [Optional] Zero or more dimensions to group results by.
	Type       string   `json:"type" yaml:"Type"`             // [Optional] Filter results to the following type
	// TODO: dimensionFilterGroups
	AggregationType string `json:"aggregationType" yaml:"AggregationType"` // [Optional] How data is aggregated.
	RowLimit        int    `json:"rowLimit" yaml:"RowLimit"`               // [Optional; Valid range is 1–25,000; Default is 1,000] The maximum number of rows to return. To page through results, use the startRow offset.
	StartRow        int    `json:"startRow" yaml:"StartRow"`               // [Optional; Default is 0] Zero-based index of the first row in the response. Must be a non-negative number. If startRow exceeds the number of results for the query, the response will be a successful response with zero rows.
	DataState       string `json:"dataState" yaml:"DataState"`             // [Optional] If "all" (case-insensitive), data will include fresh data. If "final" (case-insensitive) or if this parameter is omitted, the returned data will include only finalized data.
}

func (*QueryParameters) String

func (r *QueryParameters) String() string

String implements the Stringer interface.

The returned string is in YAML format.

If failed to marshal to YAML, returns the pretty-print format ("%#v")

type QueryResponse

type QueryResponse struct {
	Rows                    []Row  `json:"rows" yaml:"Rows"`                                       // A list of rows grouped by the key values in the order given in the query.
	ResponseAggregationType string `json:"responseAggregationType" yaml:"ResponseAggregationType"` // How the results were aggregated.
}

func Query

func Query(siteUrl string, params *QueryParameters) (*QueryResponse, error)

Query uses SearchConsole.Query with DefaultSearchConsole.

type RobotsTxtState

type RobotsTxtState string
const (
	RobotsTxtStateUnspecified RobotsTxtState = "ROBOTS_TXT_STATE_UNSPECIFIED" // Unknown robots.txt state, typically because the page wasn't fetched or found, or because robots.txt itself couldn't be reached.
	RobotsTxtStateAllowed     RobotsTxtState = "ALLOWED"                      // Crawl allowed by robots.txt.
	RobotsTxtStateDisallowed  RobotsTxtState = "DISALLOWED"                   // Crawl blocked by robots.txt.
)

type Row

type Row struct {
	Keys        []string `json:"keys" yaml:"Keys"`               // A list of the dimension values for that row, grouped according to the dimensions in the request, in the order specified in the request.
	Clicks      float64  `json:"clicks" yaml:"Clicks"`           // Click count for the row.
	Impressions float64  `json:"impressions" yaml:"Impressions"` // Impression count for the row.
	Ctr         float64  `json:"ctr" yaml:"Ctr"`                 // Click Through Rate (CTR) for the row. Values range from 0 to 1.0, inclusive.
	Position    float64  `json:"position" yaml:"Position"`       // Average position in search results.
}

type SearchConsole

type SearchConsole struct {
	// contains filtered or unexported fields
}
var DefaultSearchConsole *SearchConsole

func NewSearchConsole

func NewSearchConsole(auth authentication.Authenticator) *SearchConsole

func NewSearchConsoleFromJSON

func NewSearchConsoleFromJSON(data []byte) (*SearchConsole, error)

NewSearchConsoleFromJSON parses a Service Account JSON from data and returns a new *SearchConsole.

func NewSearchConsoleFromJSONFile

func NewSearchConsoleFromJSONFile(name string) (*SearchConsole, error)

NewSearchConsoleFromJSONFile parses a Service Account JSON file in path name and returns a new *SearchConsole.

func (*SearchConsole) AddSite

func (sc *SearchConsole) AddSite(siteUrl string) error

AddSite adds a site to the set of the user's sites in Search Console.

If successful, this method returns an empty response body. If the body not empty, returns it as an error.

This function sets the Oauth2 scope to WebmastersScope.

See more: https://developers.google.com/webmaster-tools/v1/sites/add

func (*SearchConsole) DeleteSite

func (sc *SearchConsole) DeleteSite(siteUrl string) error

DeleteSite removes a site from the set of the user's Search Console sites.

If successful, this method returns an empty response body. If the body not empty, returns it as an error.

This function sets the Oauth2 scope to WebmastersScope.

See more: https://developers.google.com/webmaster-tools/v1/sites/delete

func (*SearchConsole) DeleteSitemap

func (sc *SearchConsole) DeleteSitemap(siteUrl string, feedpath string) error

DeleteSitemap deletes a sitemap from this site.

If successful, this method returns an empty response body. If the body not empty, returns it as an error.

This function sets the Oauth2 scope to WebmastersScope.

See more: https://developers.google.com/webmaster-tools/v1/sitemaps/delete

func (*SearchConsole) GetSite

func (sc *SearchConsole) GetSite(siteUrl string) (Site, error)

GetSite retrieves information about specific site.

This function sets the Oauth2 scope to WebmastersReadScope.

See more: https://developers.google.com/webmaster-tools/v1/sites/get

func (*SearchConsole) GetSitemap

func (sc *SearchConsole) GetSitemap(siteUrl string, feedpath string) (Sitemap, error)

GetSite retrieves information about a specific sitemap.

This function sets the Oauth2 scope to WebmastersReadScope.

See more: https://developers.google.com/webmaster-tools/v1/sitemaps/get

func (*SearchConsole) Inspect

func (sc *SearchConsole) Inspect(inspectionUrl, siteUrl, languageCode string) (*UrlInspectionResult, error)

Inspect provides information about the provided URL in the Google index. View the indexed, or indexable, status of the provided URL. Presently only the status of the version in the Google index is available; you cannot test the indexability of a live URL.

  • inspectionUrl: Required. Fully-qualified URL to inspect. Must be under the property specified in "siteUrl".

  • siteUrl: Required. The URL of the property as defined in Search Console. Note that URL-prefix properties must include a trailing / mark. Examples: https://www.example.com/ for a URL-prefix property, or sc-domain:example.com for a Domain property.

  • languageCode: Optional. An IETF BCP-47 language code representing the requested language for translated issue messages, e.g. "en-US", "or "de-CH". Default value is "en-US".

See more: https://developers.google.com/webmaster-tools/v1/urlInspection.index/inspect

func (*SearchConsole) KnownPages

func (sc *SearchConsole) KnownPages(siteUrl string) ([]string, error)

KnownPages uses Query with parameters AllKnownPagesQueryParameters to get all known pages from Search Console.

TODO: Use [QueryParameters.StartRow] if the result is greater than 25000.

func (*SearchConsole) ListSitemaps

func (sc *SearchConsole) ListSitemaps(siteUrl string) ([]Sitemap, error)

ListSitemaps lists the sitemaps-entries submitted for this site, or included in the sitemap index file (if sitemapIndex is specified in the request).

This function sets the Oauth2 scope to WebmastersReadScope.

See more: https://developers.google.com/webmaster-tools/v1/sitemaps/list

func (*SearchConsole) ListSites

func (sc *SearchConsole) ListSites() ([]Site, error)

ListSites lists the user's Search Console sites.

This function sets the Oauth2 scope to WebmastersReadScope.

See more: https://developers.google.com/webmaster-tools/v1/sites/list

func (*SearchConsole) Query

func (sc *SearchConsole) Query(siteUrl string, params *QueryParameters) (*QueryResponse, error)

Query your search traffic data of siteUrl (either "sc-domain:example.com" or "https://example.com) with filters and parameters that you define. The method returns zero or more rows grouped by the row keys (dimensions) that you define. You must define a date range of one or more days.

This function sets the Oauth2 scope to WebmastersReadScope.

See more: https://developers.google.com/webmaster-tools/v1/searchanalytics/query

func (*SearchConsole) SubmitSitemap

func (sc *SearchConsole) SubmitSitemap(siteUrl string, feedpath string) error

SubmitSitemap submits a sitemap for a site.

If successful, this method returns an empty response body. If the body not empty, returns it as an error.

This function sets the Oauth2 scope to WebmastersScope.

See more: https://developers.google.com/webmaster-tools/v1/sitemaps/submit

type Site

type Site struct {
	URL        string `json:"siteUrl" yaml:"SiteURL"`
	Permission string `json:"permissionLevel" yaml:"PermissionLevel"`
}

func GetSite

func GetSite(siteUrl string) (Site, error)

GetSite uses SearchConsole.GetSite with DefaultSearchConsole.

func ListSites

func ListSites() ([]Site, error)

ListSites uses SearchConsole.ListSites with DefaultSearchConsole.

func (Site) String

func (s Site) String() string

type Sitemap

type Sitemap struct {
	Path            string           `json:"path" yaml:"Path"`                       // The url of the sitemap.
	LastSubmitted   time.Time        `json:"lastSubmitted" yaml:"LastSubmitted"`     // Date & time in which this sitemap was submitted. Date format is in RFC 3339 format (yyyy-mm-dd).
	IsPending       bool             `json:"isPending" yaml:"IsPending"`             // If true, the sitemap has not been processed.
	IsSitemapsIndex bool             `json:"isSitemapsIndex" yaml:"IsSitemapsIndex"` // If true, the sitemap is a collection of sitemaps.
	Type            SitemapType      `json:"type" yaml:"Type"`                       // The type of the sitemap.
	LastDownloaded  time.Time        `json:"lastDownloaded" yaml:"LastDownloaded"`   // Date & time in which this sitemap was last downloaded. Date format is in RFC 3339 format (yyyy-mm-dd).
	Warnings        int              `json:"warnings,string" yaml:"Warnings"`        // Number of warnings for the sitemap. These are generally non-critical issues with URLs in the sitemaps.
	Errors          int              `json:"errors,string" yaml:"Errors"`            // Number of errors in the sitemap. These are issues with the sitemap itself that need to be fixed before it can be processed correctly.
	Contents        []SitemapContent `json:"contents" yaml:"Contents"`               // The various content types in the sitemap.
}

func GetSitemap

func GetSitemap(siteUrl string, feedpath string) (Sitemap, error)

GetSitemap uses SearchConsole.GetSitemap with DefaultSearchConsole.

func ListSitemaps

func ListSitemaps(siteUrl string) ([]Sitemap, error)

ListSitemaps uses SearchConsole.ListSitemaps with DefaultSearchConsole.

func (*Sitemap) String

func (s *Sitemap) String() string

String implements the Stringer interface.

The returned string is in YAML format.

If failed to marshal to YAML, returns the pretty-print format ("%#v")

type SitemapContent

type SitemapContent struct {
	Type      SitemapContentType `json:"type" yaml:"Type"`                  // The specific type of content in this sitemap.
	Submitted int                `json:"submitted,string" yaml:"Submitted"` // The number of URLs in the sitemap (of the content type).
	Indexed   int                `json:"indexed,string" yaml:"Indexed"`     // Deprecated; do not use.
}

type SitemapContentType

type SitemapContentType string
const (
	SitemapContentTypeAndroidApp SitemapContentType = "androidApp"
	SitemapContentTypeImage      SitemapContentType = "image"
	SitemapContentTypeIosApp     SitemapContentType = "iosApp"
	SitemapContentTypeMobile     SitemapContentType = "mobile"
	SitemapContentTypeNews       SitemapContentType = "news"
	SitemapContentTypePattern    SitemapContentType = "pattern"
	SitemapContentTypeVideo      SitemapContentType = "video"
	SitemapContentTypeWeb        SitemapContentType = "web"
)

type SitemapType

type SitemapType string
const (
	SitemapTypeAtomFeed       SitemapType = "atomFeed"
	SitemapTypeNotSitemap     SitemapType = "notSitemap"
	SitemapTypePatternSitemap SitemapType = "patternSitemap"
	SitemapTypeRssFeed        SitemapType = "rssFeed"
	SitemapTypeSitemap        SitemapType = "sitemap"
	SitemapTypeUrlList        SitemapType = "urlList"
)

type UrlInspectionResult

type UrlInspectionResult struct {
	InspectionResultLink string                      `json:"inspectionResultLink" yaml:"InspectionResultLink"` // Link to Search Console URL inspection.
	IndexStatusResult    IndexStatusInspectionResult `json:"indexStatusResult" yaml:"IndexStatusResult"`       // Result of the index status analysis.
	AmpResult            AmpInspectionResult         `json:"ampResult" yaml:"AmpResult"`                       // Result of the AMP analysis. Absent if the page is not an AMP page.
}

URL inspection result, including all inspection results.

TODO:

  • richResultsResult

func Inspect

func Inspect(inspectionUrl, siteUrl, languageCode string) (*UrlInspectionResult, error)

Inspect uses SearchConsole.Inspect with DefaultSearchConsole.

func (*UrlInspectionResult) String

func (r *UrlInspectionResult) String() string

String implements the Stringer interface.

The returned string is in YAML format.

If failed to marshal to YAML, returns the pretty-print format ("%#v")

type Verdict

type Verdict string
const (
	VerdictUnspecified Verdict = "VERDICT_UNSPECIFIED" // Unknown verdict.
	VerdictPass        Verdict = "PASS"                // Equivalent to "Valid" for the page or item in Search Console.
	VerdictPartial     Verdict = "PARTIAL"             // Reserved, no longer in use.
	VerdictFail        Verdict = "FAIL"                // Equivalent to "Error" or "Invalid" for the page or item in Search Console.
	VerdictNeutral     Verdict = "NEUTRAL"             // Equivalent to "Excluded" for the page or item in Search Console.
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL