Compare commits

..

No commits in common. "master" and "v0.0.4" have entirely different histories.

3 changed files with 14 additions and 46 deletions

View File

@ -1,4 +1,2 @@
# download # download

View File

@ -7,7 +7,6 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"strings"
"github.com/tanaikech/go-getfilelist" "github.com/tanaikech/go-getfilelist"
"google.golang.org/api/drive/v3" "google.golang.org/api/drive/v3"
@ -85,52 +84,36 @@ func (g GoogleDrive) GetFilesByFolderID(folderID string, mimeType []string) ([]G
return result, nil return result, nil
} }
// DownloadByFileID download file into specific path func (g GoogleDrive) DownloadByFileID(id, name, location string) (err error) {
func (g GoogleDrive) DownloadByFileID(id, path string) (filename string, err error) { fmt.Printf("[google drive] start download file %s \n", name)
// trim "/" in the end of path defer fmt.Printf("[google drive] done download file %s \n", name)
path = strings.TrimSuffix(path, "/")
// prepare url
url := fmt.Sprintf("https://drive.google.com/uc?export=download&id=%s", id) 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 // Get the data
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
return "", err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
// Check server response // Check server response
if resp.StatusCode != http.StatusOK { 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 // Writer the body to file
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
if err != nil { if err != nil {
return "", err return err
} }
return filename, nil return nil
} }

13
util.go
View File

@ -1,13 +0,0 @@
package download
import (
"mime"
)
func getFileNameFromHeaderContentDisposition(value string) string {
disposition, params, err := mime.ParseMediaType(value)
if err != nil || disposition != "attachment" {
return ""
}
return params["filename"]
}