从Google云端硬盘下载公共文件 - Golang

时间:2013-08-11 22:38:55

标签: download go google-drive-api

我在Google云端硬盘上存储了一个zip文件(公开共享)。我想知道如何在Golang中下载它。这个当前代码只创建一个名为“file.zip”的空白文件:

package main

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

func main() {
    url := "https://docs.google.com/uc?export=download&id=0B2Q7X-dUtUBebElySVh1ZS1iaTQ"
    fileName := "file.zip"
    fmt.Println("Downloading file...")

    output, err := os.Create(fileName)
    defer output.Close()

    response, err := http.Get(url)
    if err != nil {
        fmt.Println("Error while downloading", url, "-", eerrror)
        return
    }
    defer response.Body.Close()

    n, err := io.Copy(output, response.Body)

    fmt.Println(n, "bytes downloaded")
}

3 个答案:

答案 0 :(得分:7)

这似乎是一个错误,无论是谷歌驱动器还是golang,我不确定是哪个!

问题是您提供的第一个网址会重定向到第二个看起来像这样的网址

https://doc-00-c8-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8i67l6m6cdojptjuh883mu0qqmtptds1/1376330400000/06448503420061938118/*/0B2Q7X-dUtUBebElySVh1ZS1iaTQ?h=16653014193614665626&e=download

请注意根据this stack overflow question合法的网址中的*。然而,它确实具有特殊的意义作为分隔符。

使用编码为*的{​​{1}}来获取此网址

%2A

Google将“403 Forbidden”回复给。

Google似乎没有将https://doc-00-c8-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8i67l6m6cdojptjuh883mu0qqmtptds1/1376330400000/06448503420061938118/%2A/0B2Q7X-dUtUBebElySVh1ZS1iaTQ?h=16653014193614665626&e=download解析为%2A

根据URI方案中使用的this article on wikipedia保留字符(其中*是一个):如果有必要将该字符用于其他目的,则该字符必须是百分比编码

我不足以说明谁是对的,但是既然Google写了问题的两个部分,那绝对是他们的错!

Here is the program I was using for testing

答案 1 :(得分:5)

我找到了解决方案。 使用:https://googledrive.com/host/ ID

而不是:https://docs.google.com/uc?export=download&id= ID

答案 2 :(得分:3)

我还在调查为什么会这样,同时你可以使用这个解决方法:

http://play.golang.org/p/SzGBAiZdGJ

在重定向发生时调用CheckRedirect,您可以添加不透明路径以避免URL被URL编码。

的Francesc