github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/build/kubefile/parser/file_fetcher.go (about) 1 // Copyright © 2022 Alibaba Group Holding Ltd. 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 parser 16 17 import ( 18 "io" 19 "net/http" 20 "net/url" 21 "os" 22 "path" 23 "path/filepath" 24 25 "github.com/pkg/errors" 26 "github.com/sirupsen/logrus" 27 ) 28 29 func getFileFromURL(src, rename, mountPoint string) (filePath string, err error) { 30 url, err := url.Parse(src) 31 if err != nil { 32 return "", err 33 } 34 response, err := http.Get(src) /* #nosec G107 */ 35 if err != nil { 36 return "", err 37 } 38 defer func(Body io.ReadCloser) { 39 err := Body.Close() 40 if err != nil { 41 logrus.Warnf("failed to close http reader") 42 } 43 }(response.Body) 44 // Figure out what to name the new content. 45 name := rename 46 if name == "" { 47 name = path.Base(url.Path) 48 } 49 target := filepath.Clean(filepath.Join(mountPoint, name)) 50 f, err := os.Create(target) 51 if err != nil { 52 return "", errors.Wrapf(err, "error creating file to target %s for %s", target, src) 53 } 54 defer func() { 55 _ = f.Close() 56 }() 57 _, err = io.Copy(f, response.Body) 58 if err != nil { 59 return "", errors.Wrapf(err, "error writing %q to temporary file %q", src, f.Name()) 60 } 61 return target, nil 62 }