MM-27918 In-Product notices support (#15316)

Этот коммит содержится в:
Eli Yukelzon
2020-09-21 10:28:46 +03:00
коммит произвёл GitHub
родитель 43ed6ad690
Коммит 4e9ddd4686
63 изменённых файлов: 4549 добавлений и 7 удалений

Просмотреть файл

@@ -4,6 +4,8 @@
package utils
import (
"github.com/pkg/errors"
"io/ioutil"
"net"
"net/http"
"net/url"
@@ -121,3 +123,52 @@ func GetHostnameFromSiteURL(siteURL string) string {
return u.Hostname()
}
type RequestCache struct {
Data []byte
Date string
Key string
}
// Fetch JSON data from the notices server
// if skip is passed, does a fetch without touching the cache
func GetUrlWithCache(url string, cache *RequestCache, skip bool) ([]byte, error) {
// Build a GET Request, including optional If-None-Match header.
req, err := http.NewRequest("GET", url, nil)
if err != nil {
cache.Data = nil
return nil, err
}
if !skip && cache.Data != nil {
req.Header.Add("If-None-Match", cache.Key)
req.Header.Add("If-Modified-Since", cache.Date)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
cache.Data = nil
return nil, err
}
defer resp.Body.Close()
// No change from latest known Etag?
if resp.StatusCode == http.StatusNotModified {
return cache.Data, nil
}
if resp.StatusCode != 200 {
cache.Data = nil
return nil, errors.Errorf("Fetching notices failed with status code %d", resp.StatusCode)
}
cache.Data, err = ioutil.ReadAll(resp.Body)
if err != nil {
cache.Data = nil
return nil, err
}
// If etags headers are missing, ignore.
cache.Key = resp.Header.Get("ETag")
cache.Date = resp.Header.Get("Date")
return cache.Data, err
}