github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/shared/fetch_runs.go (about)

     1  // Copyright 2017 The WPT Dashboard Project. All rights reserved.
     2  // Use of this source code is governed by a BSD-style license that can be
     3  // found in the LICENSE file.
     4  
     5  package shared
     6  
     7  import (
     8  	"encoding/json"
     9  	"errors"
    10  	"io/ioutil"
    11  	"log"
    12  	"net/http"
    13  	"strconv"
    14  )
    15  
    16  // FetchLatestRuns fetches the TestRun metadata for the latest runs, using the
    17  // API on the given host.
    18  func FetchLatestRuns(wptdHost string) (TestRuns, error) {
    19  	return FetchRuns(wptdHost, TestRunFilter{})
    20  }
    21  
    22  // FetchRuns fetches the TestRun metadata for the given sha / labels, using the
    23  // API on the given host.
    24  func FetchRuns(wptdHost string, filter TestRunFilter) (TestRuns, error) {
    25  	url := "https://" + wptdHost + "/api/runs"
    26  	url += "?" + filter.OrDefault().ToQuery().Encode()
    27  
    28  	var runs TestRuns
    29  	err := FetchJSON(url, &runs)
    30  	return runs, err
    31  }
    32  
    33  // FetchJSON fetches the given URL, which is expected to be JSON, and unmarshals
    34  // it into the given value pointer, fatally logging any errors.
    35  func FetchJSON(url string, value interface{}) error {
    36  	log.Printf("Fetching %s...", url)
    37  
    38  	resp, err := http.Get(url)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	if resp.StatusCode != 200 {
    43  		return errors.New("Bad response code from " + url + ": " +
    44  			strconv.Itoa(resp.StatusCode))
    45  	}
    46  	defer resp.Body.Close()
    47  	body, err := ioutil.ReadAll(resp.Body)
    48  	if err != nil {
    49  		return err
    50  	}
    51  	return json.Unmarshal(body, value)
    52  }