File size: 771 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

// fetchFile will download and open a file with the contents of `url`.
func fetchFile(url string) (*os.File, int64, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, 0, fmt.Errorf("fetch: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil, 0, fmt.Errorf("non-200 response: %s", resp.Status)
	}

	fd, err := os.CreateTemp("", "*.zip")
	if err != nil {
		return nil, 0, fmt.Errorf("create temp file: %w", err)
	}

	n, err := io.Copy(fd, resp.Body)
	if err != nil {
		fd.Close()
		return nil, 0, fmt.Errorf("download file '%s': %w", url, err)
	}
	_, err = fd.Seek(0, 0)
	if err != nil {
		fd.Close()
		return nil, 0, fmt.Errorf("seek: %w", err)
	}

	return fd, n, nil
}