github.com/ubuntu/ubuntu-report@v1.7.4-0.20240410144652-96f37d845fac/internal/sender/send.go (about)

     1  package sender
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/url"
     8  	"path"
     9  	"time"
    10  
    11  	"github.com/pkg/errors"
    12  	log "github.com/sirupsen/logrus"
    13  )
    14  
    15  // BaseURL server to send metrics to
    16  const BaseURL = "https://metrics.ubuntu.com"
    17  
    18  // Send to url the json data
    19  func Send(url string, data []byte) error {
    20  	log.Debugf("sending %s to %s", data, url)
    21  	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
    22  	if err != nil {
    23  		return errors.Wrap(err, "couldn't create http request")
    24  	}
    25  	req.Header.Set("Content-Type", "application/json")
    26  
    27  	client := &http.Client{
    28  		Timeout: time.Second * 10,
    29  	}
    30  	resp, err := client.Do(req)
    31  	if err != nil {
    32  		return errors.Wrap(err, "couldn't send post http request")
    33  	}
    34  	defer resp.Body.Close()
    35  
    36  	if resp.StatusCode != http.StatusOK {
    37  		return errors.Errorf("incorrect status code received: %s", resp.Status)
    38  	}
    39  
    40  	_, err = ioutil.ReadAll(resp.Body)
    41  	return errors.Wrap(err, "POST body answer contained an error")
    42  }
    43  
    44  // GetURL with distro and version marshalling
    45  func GetURL(URL, distro, version string) (string, error) {
    46  	u, err := url.Parse(URL)
    47  	if err != nil {
    48  		return "", errors.Wrapf(err, "invalid base URL: %s", URL)
    49  	}
    50  	u.Path = path.Join(u.Path, distro, "desktop", version)
    51  	return u.String(), nil
    52  }