Compare commits
	
		
			3 Commits
		
	
	
	| Author | SHA1 | Date | 
|---|---|---|
|  | 378fefb00c | |
|  | 893dfff492 | |
|  | 1917722b3a | 
|  | @ -7,6 +7,7 @@ import ( | |||
| 	"io" | ||||
| 	"net/http" | ||||
| 	"os" | ||||
| 	"strings" | ||||
| 
 | ||||
| 	"github.com/tanaikech/go-getfilelist" | ||||
| 	"google.golang.org/api/drive/v3" | ||||
|  | @ -84,36 +85,52 @@ func (g GoogleDrive) GetFilesByFolderID(folderID string, mimeType []string) ([]G | |||
| 	return result, nil | ||||
| } | ||||
| 
 | ||||
| func (g GoogleDrive) DownloadByFileID(id, name, location string) (err error) { | ||||
| 	fmt.Printf("[google drive] start download file %s \n", name) | ||||
| 	defer fmt.Printf("[google drive] done download file %s \n", name) | ||||
| // DownloadByFileID download file into specific path
 | ||||
| func (g GoogleDrive) DownloadByFileID(id, path string) (filename string, err error) { | ||||
| 	// trim "/" in the end of path
 | ||||
| 	path = strings.TrimSuffix(path, "/") | ||||
| 
 | ||||
| 	// prepare url
 | ||||
| 	url := fmt.Sprintf("https://drive.google.com/uc?export=download&id=%s", id) | ||||
| 
 | ||||
| 	// Create the file
 | ||||
| 	out, err := os.Create(location) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
| 	defer out.Close() | ||||
| 
 | ||||
| 	// Get the data
 | ||||
| 	resp, err := http.Get(url) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 		return "", err | ||||
| 	} | ||||
| 	defer resp.Body.Close() | ||||
| 
 | ||||
| 	// Check server response
 | ||||
| 	if resp.StatusCode != http.StatusOK { | ||||
| 		return fmt.Errorf("bad status: %s", resp.Status) | ||||
| 		return "", fmt.Errorf("bad status: %s", resp.Status) | ||||
| 	} | ||||
| 
 | ||||
| 	// get file name
 | ||||
| 	filename = getFileNameFromHeaderContentDisposition(resp.Header.Get("Content-Disposition")) | ||||
| 
 | ||||
| 	// return err if not found
 | ||||
| 	if filename == "" { | ||||
| 		return "", errors.New("file is not existed or is in private mode, please check again") | ||||
| 	} | ||||
| 
 | ||||
| 	// assign location with field name
 | ||||
| 	location := fmt.Sprintf("%s/%s", path, filename) | ||||
| 
 | ||||
| 	// Create the file
 | ||||
| 	out, err := os.Create(location) | ||||
| 	if err != nil { | ||||
| 		return "", err | ||||
| 	} | ||||
| 	defer out.Close() | ||||
| 
 | ||||
| 	fmt.Printf("[google drive] start download file %s with id %s \n", filename, id) | ||||
| 	defer fmt.Printf("[google drive] done download file %s with id %s \n", filename, id) | ||||
| 
 | ||||
| 	// Writer the body to file
 | ||||
| 	_, err = io.Copy(out, resp.Body) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 		return "", err | ||||
| 	} | ||||
| 
 | ||||
| 	return nil | ||||
| 	return filename, nil | ||||
| } | ||||
|  |  | |||
		Loading…
	
		Reference in New Issue