sslobodr | d046be8 | 2019-01-16 10:02:22 -0500 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2017 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package discovery |
| 18 | |
| 19 | import ( |
| 20 | "net/http" |
| 21 | "path/filepath" |
| 22 | |
| 23 | "github.com/gregjones/httpcache" |
| 24 | "github.com/gregjones/httpcache/diskcache" |
| 25 | "github.com/peterbourgon/diskv" |
| 26 | "k8s.io/klog" |
| 27 | ) |
| 28 | |
| 29 | type cacheRoundTripper struct { |
| 30 | rt *httpcache.Transport |
| 31 | } |
| 32 | |
| 33 | // newCacheRoundTripper creates a roundtripper that reads the ETag on |
| 34 | // response headers and send the If-None-Match header on subsequent |
| 35 | // corresponding requests. |
| 36 | func newCacheRoundTripper(cacheDir string, rt http.RoundTripper) http.RoundTripper { |
| 37 | d := diskv.New(diskv.Options{ |
| 38 | BasePath: cacheDir, |
| 39 | TempDir: filepath.Join(cacheDir, ".diskv-temp"), |
| 40 | }) |
| 41 | t := httpcache.NewTransport(diskcache.NewWithDiskv(d)) |
| 42 | t.Transport = rt |
| 43 | |
| 44 | return &cacheRoundTripper{rt: t} |
| 45 | } |
| 46 | |
| 47 | func (rt *cacheRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 48 | return rt.rt.RoundTrip(req) |
| 49 | } |
| 50 | |
| 51 | func (rt *cacheRoundTripper) CancelRequest(req *http.Request) { |
| 52 | type canceler interface { |
| 53 | CancelRequest(*http.Request) |
| 54 | } |
| 55 | if cr, ok := rt.rt.Transport.(canceler); ok { |
| 56 | cr.CancelRequest(req) |
| 57 | } else { |
| 58 | klog.Errorf("CancelRequest not implemented by %T", rt.rt.Transport) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func (rt *cacheRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt.Transport } |