Created
January 3, 2018 02:49
-
-
Save wagoodman/371c446fbde051f94d8eac1cddc3bf73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/url" | |
"os" | |
"path" | |
"runtime" | |
"strconv" | |
"strings" | |
"time" | |
"github.com/cavaliercoder/grab" | |
) | |
func checkError(err error, message string) { | |
if err != nil { | |
fmt.Println("Error:") | |
_, file, line, _ := runtime.Caller(1) | |
fmt.Println("Line:", line, "\tFile:", file, "\n", err) | |
os.Exit(1) | |
} | |
} | |
func getFilename(urlStr string) string { | |
uri, err := url.Parse(urlStr) | |
checkError(err, "Unable to parse URI") | |
pathElements := strings.Split(uri.Path, "/") | |
return pathElements[len(pathElements)-1] | |
} | |
func downloadAsset(uri string) { | |
var request *grab.Request | |
client := grab.NewClient() | |
filepath := path.Join("/tmp/", getFilename(uri)) | |
request, _ = grab.NewRequest(filepath, uri) | |
// workaround for https://github.com/cavaliercoder/grab/issues/25, allow the ability to follow 302s | |
// request.IgnoreBadStatusCodes = true | |
fmt.Println("Downloading assets") | |
response := client.Do(request) | |
t := time.NewTicker(100 * time.Millisecond) | |
defer t.Stop() | |
Loop: | |
for { | |
select { | |
case <-t.C: | |
fmt.Println(response.Request.URL().String() + " : " + strconv.Itoa(int(100*response.Progress()))) | |
case <-response.Done: | |
fmt.Println(response.Request.URL().String() + " : Complete") | |
break Loop | |
} | |
} | |
// verify no download errors | |
if err := response.Err(); err != nil { | |
fmt.Printf("Failed to download '%s': %s\n", response.Request.URL(), err.Error()) | |
} | |
if response.HTTPResponse.StatusCode > 399 || response.HTTPResponse.StatusCode < 200 { | |
fmt.Printf("Failed to download '%s': Bad HTTP response code (%d)\n", response.Request.URL(), response.HTTPResponse.StatusCode) | |
} | |
} | |
func main() { | |
downloadAsset("https://github.com/wagoodman/bashful/releases/download/v0.0.5/bashful_Linux-x86_64") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment