Plugins: force http cache by setting cache headers (#18601)
This commit is contained in:
parent
c6ddc9b856
commit
87e1c929a9
2 changed files with 40 additions and 27 deletions
|
|
@ -23,11 +23,7 @@ type HTTP struct {
|
|||
url, method string
|
||||
headers map[string]string
|
||||
body string
|
||||
cache time.Duration
|
||||
updated time.Time
|
||||
pipeline *pipeline.Pipeline
|
||||
val []byte // Cached http response value
|
||||
err error // Cached http response error
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
|
@ -99,7 +95,6 @@ func NewHTTP(log *util.Logger, method, uri string, insecure bool, cache time.Dur
|
|||
Helper: request.NewHelper(log),
|
||||
url: uri,
|
||||
method: method,
|
||||
cache: cache,
|
||||
}
|
||||
|
||||
// http cache
|
||||
|
|
@ -108,6 +103,16 @@ func NewHTTP(log *util.Logger, method, uri string, insecure bool, cache time.Dur
|
|||
Transport: p.Client.Transport,
|
||||
}
|
||||
|
||||
if cache > 0 {
|
||||
cacheHeader := fmt.Sprintf("max-age=%d, must-revalidate", int(cache.Seconds()))
|
||||
p.Client.Transport = &transport.Decorator{
|
||||
Decorator: transport.DecorateHeaders(map[string]string{
|
||||
"Cache-Control": cacheHeader,
|
||||
}),
|
||||
Base: p.Client.Transport,
|
||||
}
|
||||
}
|
||||
|
||||
// ignore the self signed certificate
|
||||
if insecure {
|
||||
p.Client.Transport = request.NewTripper(log, transport.Insecure())
|
||||
|
|
@ -152,30 +157,27 @@ func (p *HTTP) WithAuth(typ, user, password string) (*HTTP, error) {
|
|||
|
||||
// request executes the configured request or returns the cached value
|
||||
func (p *HTTP) request(url string, body string) ([]byte, error) {
|
||||
if time.Since(p.updated) >= p.cache {
|
||||
var b io.Reader
|
||||
if p.method != http.MethodGet {
|
||||
b = strings.NewReader(body)
|
||||
}
|
||||
|
||||
url := util.DefaultScheme(url, "http")
|
||||
|
||||
// empty method becomes GET
|
||||
req, err := request.New(p.method, url, b, p.headers)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
p.val, p.err = p.DoBody(req)
|
||||
if p.err != nil {
|
||||
if err := knownErrors(p.val); err != nil {
|
||||
p.err = err
|
||||
}
|
||||
}
|
||||
p.updated = time.Now()
|
||||
var b io.Reader
|
||||
if p.method != http.MethodGet {
|
||||
b = strings.NewReader(body)
|
||||
}
|
||||
|
||||
return p.val, p.err
|
||||
url = util.DefaultScheme(url, "http")
|
||||
|
||||
// empty method becomes GET
|
||||
req, err := request.New(p.method, url, b, p.headers)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
val, err := p.DoBody(req)
|
||||
if err != nil {
|
||||
if err2 := knownErrors(val); err2 != nil {
|
||||
err = err2
|
||||
}
|
||||
}
|
||||
|
||||
return val, err
|
||||
}
|
||||
|
||||
var _ Getters = (*HTTP)(nil)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue