github.com/abdfnx/gh-api@v0.0.0-20210414084727-f5432eec23b8/pkg/cmd/run/download/http.go (about) 1 package download 2 3 import ( 4 "archive/zip" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "net/http" 9 "os" 10 11 "github.com/abdfnx/gh-api/api" 12 "github.com/abdfnx/gh-api/internal/ghrepo" 13 "github.com/abdfnx/gh-api/pkg/cmd/run/shared" 14 ) 15 16 type apiPlatform struct { 17 client *http.Client 18 repo ghrepo.Interface 19 } 20 21 func (p *apiPlatform) List(runID string) ([]shared.Artifact, error) { 22 return shared.ListArtifacts(p.client, p.repo, runID) 23 } 24 25 func (p *apiPlatform) Download(url string, dir string) error { 26 return downloadArtifact(p.client, url, dir) 27 } 28 29 func downloadArtifact(httpClient *http.Client, url, destDir string) error { 30 req, err := http.NewRequest("GET", url, nil) 31 if err != nil { 32 return err 33 } 34 // The server rejects this :( 35 //req.Header.Set("Accept", "application/zip") 36 37 resp, err := httpClient.Do(req) 38 if err != nil { 39 return err 40 } 41 defer resp.Body.Close() 42 43 if resp.StatusCode > 299 { 44 return api.HandleHTTPError(resp) 45 } 46 47 tmpfile, err := ioutil.TempFile("", "gh-artifact.*.zip") 48 if err != nil { 49 return fmt.Errorf("error initializing temporary file: %w", err) 50 } 51 defer func() { 52 _ = tmpfile.Close() 53 _ = os.Remove(tmpfile.Name()) 54 }() 55 56 size, err := io.Copy(tmpfile, resp.Body) 57 if err != nil { 58 return fmt.Errorf("error writing zip archive: %w", err) 59 } 60 61 zipfile, err := zip.NewReader(tmpfile, size) 62 if err != nil { 63 return fmt.Errorf("error extracting zip archive: %w", err) 64 } 65 if err := extractZip(zipfile, destDir); err != nil { 66 return fmt.Errorf("error extracting zip archive: %w", err) 67 } 68 69 return nil 70 }