package seo import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "time" ) // Speed is a page's Core Web Vitals from PageSpeed Insights: real Chrome // users' numbers when Google has enough of them, and the lab score. type Speed struct { Page string `json:"page"` Field bool `json:"field"` // real users' data exists LCP int `json:"lcp_ms"` INP int `json:"inp_ms"` CLS int `json:"cls_x100"` // CLS × 100 Overall string `json:"overall"` // FAST, AVERAGE, SLOW Score int `json:"score"` // Lighthouse performance, 0 to 100 Error string `json:"error,omitempty"` } // PageSpeedURL is the API's address; tests replace it. var PageSpeedURL = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed" // CheckSpeed asks PageSpeed Insights about a page, on mobile. The key is // optional; without one Google allows only a few requests. func CheckSpeed(ctx context.Context, page, key string) Speed { s := Speed{Page: page} q := url.Values{"url": {page}, "strategy": {"mobile"}, "category": {"performance"}} if key != "" { q.Set("key", key) } ctx, cancel := context.WithTimeout(ctx, 90*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, PageSpeedURL+"?"+q.Encode(), nil) if err != nil { s.Error = err.Error() return s } res, err := http.DefaultClient.Do(req) if err != nil { s.Error = err.Error() return s } defer res.Body.Close() raw, _ := io.ReadAll(io.LimitReader(res.Body, 16<<20)) if res.StatusCode != http.StatusOK { var e struct { Error struct { Message string `json:"message"` } `json:"error"` } _ = json.Unmarshal(raw, &e) s.Error = fmt.Sprintf("PageSpeed Insights: HTTP %d %s", res.StatusCode, e.Error.Message) return s } var out struct { Loading struct { Metrics map[string]struct { Percentile int `json:"percentile"` } `json:"metrics"` Overall string `json:"overall_category"` } `json:"loadingExperience"` Lighthouse struct { Categories struct { Performance struct { Score float64 `json:"score"` } `json:"performance"` } `json:"categories"` } `json:"lighthouseResult"` } if err := json.Unmarshal(raw, &out); err != nil { s.Error = err.Error() return s } m := out.Loading.Metrics if len(m) > 0 { s.Field = true s.LCP = m["LARGEST_CONTENTFUL_PAINT_MS"].Percentile s.INP = m["INTERACTION_TO_NEXT_PAINT"].Percentile s.CLS = m["CUMULATIVE_LAYOUT_SHIFT_SCORE"].Percentile s.Overall = out.Loading.Overall } s.Score = int(out.Lighthouse.Categories.Performance.Score*100 + 0.5) return s } // Good, needs improvement or poor, by Google's Core Web Vitals limits. func (s Speed) LCPRating() string { return rate(float64(s.LCP), 2500, 4000) } func (s Speed) INPRating() string { return rate(float64(s.INP), 200, 500) } func (s Speed) CLSRating() string { return rate(float64(s.CLS)/100, 0.1, 0.25) } func rate(v, good, poor float64) string { switch { case v <= good: return "good" case v <= poor: return "needs improvement" } return "poor" }