gitee.com/mirrors/gauge@v1.0.6/util/httpUtils.go (about) 1 // Copyright 2015 ThoughtWorks, Inc. 2 3 // This file is part of Gauge. 4 5 // Gauge is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 10 // Gauge is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 15 // You should have received a copy of the GNU General Public License 16 // along with Gauge. If not, see <http://www.gnu.org/licenses/>. 17 18 package util 19 20 import ( 21 "fmt" 22 "io" 23 "net/http" 24 "os" 25 "path/filepath" 26 27 "github.com/getgauge/gauge/logger" 28 29 "github.com/getgauge/common" 30 ) 31 32 // progressReader is for indicating the download / upload progress on the console 33 type progressReader struct { 34 io.Reader 35 bytesTransfered int64 36 totalBytes int64 37 progress float64 38 progressDisplayed bool 39 } 40 41 // Read overrides the underlying io.Reader's Read method. 42 // io.Copy() will be calling this method. 43 func (w *progressReader) Read(p []byte) (int, error) { 44 n, err := w.Reader.Read(p) 45 if n > 0 { 46 w.bytesTransfered += int64(n) 47 percent := float64(w.bytesTransfered) * float64(100) / float64(w.totalBytes) 48 if percent-w.progress > 4 { 49 fmt.Print(".") 50 w.progress = percent 51 w.progressDisplayed = true 52 } 53 } 54 return n, err 55 } 56 57 // Download fires a HTTP GET request to download a resource to target directory 58 func Download(url, targetDir, fileName string, silent bool) (string, error) { 59 if !common.DirExists(targetDir) { 60 return "", fmt.Errorf("Error downloading file: %s\nTarget dir %s doesn't exists.", url, targetDir) 61 } 62 63 if fileName == "" { 64 fileName = filepath.Base(url) 65 } 66 targetFile := filepath.Join(targetDir, fileName) 67 68 logger.Debugf(true, "Downloading %s", url) 69 resp, err := http.Get(url) 70 if err != nil { 71 return "", err 72 } 73 if resp.StatusCode != 200 { 74 return "", fmt.Errorf("Error downloading file: %s.\n%s", url, resp.Status) 75 } 76 77 defer resp.Body.Close() 78 79 out, err := os.Create(targetFile) 80 if err != nil { 81 return "", err 82 } 83 defer out.Close() 84 if silent { 85 _, err = io.Copy(out, resp.Body) 86 } else { 87 progressReader := &progressReader{Reader: resp.Body, totalBytes: resp.ContentLength} 88 _, err = io.Copy(out, progressReader) 89 if progressReader.progressDisplayed { 90 fmt.Println() 91 } 92 } 93 return targetFile, err 94 }