Golang http 获取空response.Body

Ent*_*Zha 5 http go web google-drive-api

我遇到一个问题,对于某些 url,Golang 中的代码无法检索预期的内容。我没有发布实际的网址,但它具有这种形式,并且是谷歌驱动器文件下载的链接https://docs.google.com/uc?id=somelongid&export=download。如果我使用 wget 来获取文件,它工作正常。我也有使用的 ruby​​ 代码open()并且它也可以工作。由于某种原因,Golang 返回一个空缓冲区并且没有错误。如果我使用此代码来获取一些“普通”url(例如静态网站),它会按预期工作并返回非空response.Body。下面是我从项目中提取的代码,以简化和缩小问题可能出现的范围。下面是输出。

package main

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

func main() {
    resp, err := http.Get("myurlishere")
    if err != nil {
        fmt.Println("Something went wrong")
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("Body: %v\n", body)
    fmt.Printf("Error: %v\n", err)
}
Run Code Online (Sandbox Code Playgroud)

输出

$go run main.go
Body: []
Error: <nil>
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 2

也许您收到 HTTP 响应错误。

http.Get 例如,如果服务器使用404 - Not Found, 或进行应答,则不会400 - Bad Request返回错误。这是因为它们不是异常行为,它们是来自服务器的有效响应。

您应该检查一下resp.StatusCode,看看它是否在 200 范围内。

您可以在包文档中查看不同的状态代码。

这个问题表明用go从googledrive下载存在一些问题,因为他们在url中使用通配符,也许你可以尝试使用答案中列出的url:https://googledrive.com/host/ID