github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/cmd/plugin/download/fetch.go (about) 1 // Copyright 2019 The Kubernetes Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package download 16 17 import ( 18 "io" 19 "net/http" 20 "os" 21 22 "github.com/pkg/errors" 23 "k8s.io/klog/v2" 24 ) 25 26 type Fetcher interface { 27 // Get gets the file and returns an stream to read the file. 28 Get(uri string) (io.ReadCloser, error) 29 } 30 31 var _ Fetcher = HTTPFetcher{} 32 33 // HTTPFetcher is used to get a file from a http:// or https:// schema path. 34 type HTTPFetcher struct{} 35 36 // Get gets the file and returns a stream to read the file. 37 func (HTTPFetcher) Get(uri string) (io.ReadCloser, error) { 38 klog.V(2).Infof("Fetching %q", uri) 39 resp, err := http.Get(uri) 40 if err != nil { 41 return nil, errors.Wrapf(err, "failed to download %q", uri) 42 } 43 return resp.Body, nil 44 } 45 46 var _ Fetcher = fileFetcher{} 47 48 type fileFetcher struct{ f string } 49 50 func (f fileFetcher) Get(_ string) (io.ReadCloser, error) { 51 klog.V(2).Infof("Reading %q", f.f) 52 file, err := os.Open(f.f) 53 return file, errors.Wrapf(err, "failed to open archive file %q for reading", f.f) 54 } 55 56 // NewFileFetcher returns a local file reader. 57 func NewFileFetcher(path string) Fetcher { return fileFetcher{f: path} }