gpt4 book ai didi

go - 使用 Go 的 net/http 包连接到 YouTube API 的问题

转载 作者:IT王子 更新时间:2023-10-29 02:05:45 26 4
gpt4 key购买 nike

我认为这可能是我关于 SO 的第一个问题。我一直沉浸在 Go 中。我刚读完Go 编程简介,我只想编写一个简单的程序来查询 YT 数据 API v3。

问题:当我执行 go run request.go 时,出现 404 Not Found 错误。但是,当我获取传递的 URL 并将其粘贴到我的浏览器或 Postman 中时,请求工作正常。这是我的 func main() {} 的样子:

func main() {
// read in API key
key, error_ := ioutil.ReadFile("user_data.txt")
if error_ != nil {
log.Fatal(error_)
}
api_key += string(key)

// buil url
url := base_url + query + api_key
// Uncomment the next line to show that I'm not insane.
// url = "http://ip.jsontest.com/"

// make request
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
body, error_g := ioutil.ReadAll(resp.Body)
if error_g != nil {
fmt.Println(error_g)
}
fmt.Println(resp.Status)
fmt.Println(resp.Request)
fmt.Println(string(body))
defer resp.Body.Close()
// parse response
var vs Videos
err = json.NewDecoder(resp.Body).Decode(&vs)
if err != nil {
fmt.Printf("%T\n", err)
// fmt.Println("Error:", err)
log.Fatal(err)
}
for _, v := range vs.Items {
fmt.Println(v.Id.VideoId, v.Snippet.Title)
}
}

这是我的 repo 协议(protocol)中程序的链接 request.go

最佳答案

我很惊讶你的例子工作,假设这就是全部,因为你没有为 url := base_url + 定义 base_urlquery查询 + api_key。我宁愿将其作为评论而不是答案,但我没有足够的代表来这样做。

我假设你已经尝试过这个,但我会打印出你构建的 url 并仔细检查它看起来像

https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=YOUR_API_KEY

您应该考虑使用的另一件事是 net/url,它可能会间接解决您的问题。包来构建您的 URL。然后你可以这样做:

params := url.Values{}
params.Add("id", video_id)
params.Add("key", api_key)

url := &url.Url{
Host: 'https://www.googleapis.com/youtube/v3/videos',
Query: params.Encode()
}

get_url := url.String()

它有点乏味,但这里的优点是它会为您处理所有编码和查询构建。我的猜测是,这可能是出了问题的地方,假设您正在正确读取 API key ,并且它确实对数据 API 有效。显然,您希望将该逻辑分解为函数调用以使其更易于重用,但您明白了。

关于go - 使用 Go 的 net/http 包连接到 YouTube API 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26782572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com