Skip to content

Instantly share code, notes, and snippets.

@veggiemonk
Created April 27, 2023 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veggiemonk/4adee84a5ec0aa9e996e71c896254560 to your computer and use it in GitHub Desktop.
Save veggiemonk/4adee84a5ec0aa9e996e71c896254560 to your computer and use it in GitHub Desktop.
utility to download badge for go test coverage
func badgedl(pct float64) error {
color := ""
switch {
case pct < 50:
color = "orange"
case pct < 60:
color = "yellow"
case pct < 70:
color = "yellowgreen"
case pct < 80:
color = "green"
case pct < 90:
color = "brightgreen"
default:
color = "red"
}
u := "https://img.shields.io/badge/"
format := "coverage-%.1f%%-%s.svg"
u += url.QueryEscape(fmt.Sprintf(format, pct, color))
fmt.Println("downloading badge:", u)
if err := download(u, ".github/coverage.svg"); err != nil {
return fmt.Errorf("badge: %w", err)
}
return nil
}
func download(url, path string) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
// req.Header.Set("Content-Type", "application/json")
client := http.Client{Timeout: 30 * time.Second}
res, err := client.Do(req)
if err != nil {
return err
}
defer func() {
err = errors.Join(err, res.Body.Close())
}()
if res.StatusCode >= 400 {
return fmt.Errorf("status: %s, url: %s", res.Status, url)
}
b, err := io.ReadAll(res.Body)
if err != nil {
return err
}
err = writeBadge(path, b)
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment