google

package module
v0.0.0-...-a1a701a Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2024 License: MIT Imports: 11 Imported by: 0

README

go-google

Go Report Card Go Reference

Golang module to Google APIs.

Get:

go get github.com/g0rbe/go-google@latest

Get the latest tag (if Go module proxy is not updated):

go get "github.com/g0rbe/go-google@$(curl -s 'https://api.github.com/repos/g0rbe/go-google/tags' | jq -r '.[0].name')"

Get the latest commit (if Go module proxy is not updated):

go get "github.com/g0rbe/go-google@$(curl -s 'https://api.github.com/repos/g0rbe/go-google/commits' | jq -r '.[0].sha')"

TODO

  • Common errors

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	LighthouseCategoryAccessibility = LighthouseCategory("ACCESSIBILITY")
	LighthouseCategoryBestPractices = LighthouseCategory("BEST_PRACTICES")
	LighthouseCategoryPerformance   = LighthouseCategory("PERFORMANCE")
	LighthouseCategorySEO           = LighthouseCategory("SEO")

	// Shorthand to all PagespeedCategory
	LighthouseCategoryAll = []LighthouseParam{LighthouseCategoryAccessibility, LighthouseCategoryBestPractices, LighthouseCategoryPerformance, LighthouseCategorySEO}
)

Possible values for category paramater

View Source
var (
	LighthouseStrategyDesktop = LighthouseStrategy("dektop")
	LighthouseStrategyMobile  = LighthouseStrategy("mobile")
)

Possible values for strategy paramater

View Source
var (

	// Invalid domain
	ErrLighthouseFailedDocumentRequest = &GoogleError{
		Message: "Lighthouse returned error: FAILED_DOCUMENT_REQUEST. Lighthouse was unable to reliably load the page you requested. Make sure you are testing the correct URL and that the server is properly responding to all requests. (Details: net::ERR_CONNECTION_FAILED)",
		Domain:  "lighthouse",
		Reason:  "lighthouseUserError",
	}

	// Too much request
	ErrLighthouseUnprocessable = &GoogleError{
		Message: "Unable to process request. Please wait a while and try again.",
		Domain:  "global",
		Reason:  "internalError",
	}

	ErrLighthouseInvalidKey = &GoogleError{
		Message: "API key not valid. Please pass a valid API key.",
		Domain:  "global",
		Reason:  "badRequest",
	}

	ErrLighthouseInvalidCategory = &GoogleError{
		Message: `^Invalid value at 'category' \(type\.googleapis\.com/google\.chrome\.pagespeedonline\.v5\.PagespeedonlinePagespeedapiRunpagespeedRequest\.Category\), .*$`,
		Reason:  "invalid",
	}

	ErrLighthouseInvalidStrategy = &GoogleError{
		Message: `^Invalid value at 'strategy' \(type\.googleapis\.com/google\.chrome\.pagespeedonline\.v5\.PagespeedonlinePagespeedapiRunpagespeedRequest\.Strategy\), .*$`,
		Reason:  "invalid",
	}

	ErrLighthouseInvalidUrl = &GoogleError{
		Message:      `^Invalid value '.*'\. Values must match the following regular expression: '\(\?i\)\(url:\|origin:\)\?http\(s\)\?://\.\*'$`,
		Domain:       "gdata.CoreErrorDomain",
		Reason:       "INVALID_PARAMETER",
		Location:     "url",
		LocationType: "other",
	}

	// Rate limit
	ErrLighthouseRateLimitExceeded = &GoogleError{
		Message: `^Quota exceeded for quota metric 'Queries' and limit 'Queries per minute' of service 'pagespeedonline\.googleapis\.com' for consumer '.*'\.$`,
		Domain:  "global",
		Reason:  "rateLimitExceeded",
	}
)

Functions

func CreateLighthouseURL

func CreateLighthouseURL(u string, cred Credential, params ...LighthouseParam) (string, error)

createLighthouseURL returns the complete URL that can be passed to http.Get().

Appends the request parameters to the API endpoint.

If any error returned, that comes from Credential cred.

Types

type ApiKey

type ApiKey struct {
	// contains filtered or unexported fields
}

func NewApiKey

func NewApiKey(key string) *ApiKey

func RandomApiKeys

func RandomApiKeys(keys ...string) *ApiKey
Example
c := google.RandomApiKeys("one", "two", "three", "four", "five")

for i := 0; i < 5; i++ {

	k, err := c.Token()
	if err != nil {
		// Handle error
	}

	fmt.Printf("%s\n", k)
}
Output:

func RotatingApiKeys

func RotatingApiKeys(keys ...string) *ApiKey
Example
c := google.RotatingApiKeys("one", "two", "three", "four", "five")

for i := 0; i < 5; i++ {

	k, err := c.Token()
	if err != nil {
		// Handle error
	}

	fmt.Printf("%s\n", k)
}
Output:

two
three
four
five
one

func (*ApiKey) Token

func (k *ApiKey) Token() (string, error)

Token returns the API key. Renturns a random API key if multiple keys added with [NewApiKeys].

type Audit

type Audit struct {
	ID               string  `json:"id,omitempty"`
	Title            string  `json:"title,omitempty"`
	Description      string  `json:"description,omitempty"`
	Score            float32 `json:"score"`
	ScoreDisplayMode string  `json:"scoreDisplayMode,omitempty"`
}

type AuditRef

type AuditRef struct {
	ID     string  `json:"id,omitempty"`
	Weight float32 `json:"weight,omitempty"`
	Group  string  `json:"group,omitempty"`
}

type Category

type Category struct {
	ID                string     `json:"id,omitempty"`
	Title             string     `json:"title,omitempty"`
	Description       string     `json:"description,omitempty"`
	Score             float32    `json:"score"`
	ManualDescription string     `json:"manualDescription,omitempty"`
	AuditRefs         []AuditRef `json:"auditRefs,omitempty"`
}

type CategoryGroup

type CategoryGroup struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
}

type Credential

type Credential interface {
	Token() (string, error)
}

type Error

type Error struct {
	Code    int     `json:"code"`
	Message string  `json:"message"`
	Errors  []error `json:"errors"`
	// contains filtered or unexported fields
}

Error stores the Standard Error Messages.

See: https://developers.google.com/webmaster-tools/v1/errors

func ErrorFromResponse

func ErrorFromResponse(r *http.Response) (*Error, error)

ErrorFromResponse reads the response body and returns the Error.

The response data is stored in Error and returned by [String]

func NewError

func NewError(code int, message string) *Error

func (*Error) Error

func (e *Error) Error() string

Error returns the e.Message.

func (*Error) String

func (e *Error) String() string

String returns the stored JSON data or (if data is nil) returns e.Message.

func (*Error) UnmarshalJSON

func (e *Error) UnmarshalJSON(data []byte) error

func (*Error) Unwrap

func (e *Error) Unwrap() []error

type GoogleError

type GoogleError struct {
	Domain       string `json:"domain"`
	Reason       string `json:"reason"`
	Message      string `json:"message"`
	LocationType string `json:"locationType"`
	Location     string `json:"location"`
}

func NewGoogleError

func NewGoogleError(domain, reason, message, locationType, location string) *GoogleError

func (*GoogleError) Error

func (e *GoogleError) Error() string

func (*GoogleError) Is

func (e *GoogleError) Is(target error) bool

Is implements the errors.Is.

The Domain, Reason, LocationType and the Location fields must be equal. If the Message field is not equal, than the Message field of target can be used used as a regexp pattern to allow matching errors with dynamic fields (eg.: ErrLighthouseInvalidUrl)

type LighthouseError

type LighthouseError struct {
	URL string
	Err error
}

func NewLighthouseError

func NewLighthouseError(url string, err error) *LighthouseError

func (*LighthouseError) Error

func (e *LighthouseError) Error() string

func (*LighthouseError) Unwrap

func (e *LighthouseError) Unwrap() error

type LighthouseParam

type LighthouseParam struct {
	// contains filtered or unexported fields
}

LighthouseParam stores a single request param as a key/value pair.

func LighthouseCaptchaToken

func LighthouseCaptchaToken(v string) LighthouseParam

func LighthouseCategory

func LighthouseCategory(v string) LighthouseParam

func LighthouseLocale

func LighthouseLocale(v string) LighthouseParam

func LighthouseStrategy

func LighthouseStrategy(v string) LighthouseParam

func LighthouseURMSource

func LighthouseURMSource(v string) LighthouseParam

func LighthouseUTMCampaign

func LighthouseUTMCampaign(v string) LighthouseParam

func (LighthouseParam) Key

func (p LighthouseParam) Key() string

func (LighthouseParam) Value

func (p LighthouseParam) Value() string

type LighthouseResult

type LighthouseResult struct {
	// contains filtered or unexported fields
}

func LighthouseResultFromResponse

func LighthouseResultFromResponse(r *http.Response) (*LighthouseResult, error)

LighthouseResultFromResponse reads the LighthouseResult from an *http.Response (eg.: http.Response) and unmarshals it.

func RunConcurrentLighthouse

func RunConcurrentLighthouse(ctx context.Context, n int, u []string, cred Credential, params ...LighthouseParam) ([]*LighthouseResult, []error)

RunConcurrentLighthouse use n number of workers to run RunLighthouse() concurrently.

The Credential and the params are common across RunLighthouse functions.

func RunLighthouse

func RunLighthouse(u string, cred Credential, params ...LighthouseParam) (*LighthouseResult, error)

RunLighthouse runs PageSpeed analysis on the page at the specified URL, and returns Lighthouse scores, a list of suggestions to make that page faster, and other information.

The url parameter is required! The parameters must be specified in params. The Credential cred must be either *ApiKey or nil.

If any error occurs, the returned error is always *LighthouseError. Errors comes from other packages are wrapped in the *LighthouseError (eg.: http.Get, json.Unmarshal).

API Reference: https://developers.google.com/speed/docs/insights/rest/v5/pagespeedapi/runpagespeed

func (*LighthouseResult) Audit

func (r *LighthouseResult) Audit(name string) *Audit

Audit returns the audit with the given name.

If audit not found, returns nil.

func (*LighthouseResult) Audits

func (r *LighthouseResult) Audits() []string

Audits returns the names of the available audits.

func (*LighthouseResult) Categories

func (r *LighthouseResult) Categories() []string

Categories returns the names of the available categories.

func (*LighthouseResult) Category

func (r *LighthouseResult) Category(name string) *Category

Category returns the category with the given name.

Possible categories:

"performance"
"accessibility"

If category not found, returns nil.

func (*LighthouseResult) CategoryGroup

func (r *LighthouseResult) CategoryGroup(name string) *CategoryGroup

CategoryGroup returns the category group with the given name.

If category group not found, returns nil.

func (*LighthouseResult) CategoryGroups

func (r *LighthouseResult) CategoryGroups() []string

CategoryGroups returns the names of the available category groups.

func (*LighthouseResult) FetchTime

func (r *LighthouseResult) FetchTime() time.Time

FetchTime returns the time that this run was fetched.

func (*LighthouseResult) FinalURL

func (r *LighthouseResult) FinalURL() *url.URL

FinalURL returns the final resolved url that was audited.

func (*LighthouseResult) RequestedURL

func (r *LighthouseResult) RequestedURL() *url.URL

RequestedURL returns the original requested url.

func (*LighthouseResult) RunWarnings

func (r *LighthouseResult) RunWarnings() []error

RunWarnings returns warnings (non-fatal errors) coming from the PageSpeed API.

func (*LighthouseResult) Score

func (r *LighthouseResult) Score(category string) float32

Score returns the score of the category.

If "average" is used as category, returns the average score of the available categories. If "total" is used as category, returns the total score (adds the scores of the available categories).

If category not found returns -1.

func (*LighthouseResult) Timing

func (r *LighthouseResult) Timing() time.Duration

func (*LighthouseResult) UnmarshalJSON

func (r *LighthouseResult) UnmarshalJSON(data []byte) error

Jump to

Keyboard shortcuts

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