设置 Go-Github 和 http.Transport 的 HTTP 请求头部的方法是什么?
时间:2024-03-24
浏览:113
作者:佚名
本指南介绍了在 Go-Github 中使用 HTTP 请求标头的方法。通过利用 OAuth2 传输中的 base 字段,可以设置条件请求标头,例如 If-Modified-Since,以优化 API 调用并防止速率限制问题。使用 TransportHeaders 结构和 RoundTrip 方法,可以拦截对 RoundTrip 的调用并添加自定义标头。
我正在编写一个应用程序,它使用 github api 来查看我的 github 组织中的存储库。我正在使用 github.com/google/go-github 库。
我还使用 github.com/gregjones/httpcache,以便我可以进行基于令牌的身份验证以及为 api 调用设置条件标头。我已经进行了身份验证:
ctx := context.Background()
// GitHUb API authentication
transport = &oauth2.Transport{
Source: oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: gh.tokens.GitHub.Token,
},
),
}
// Configure HTTP memory caching
transport = &httpcache.Transport{
Transport: transport,
Cache: httpcache.NewMemoryCache(),
MarkCachedResponses: true,
}
// Create the http client that GutHUb will use
httpClient := &http.Client{
Transport: transport,
}
// Attempt to login to GitHub
client := github.NewClient(httpClient)
但是,例如,当我使用 client.repositories.get 时,我无法弄清楚如何添加必要的 if-match 标头。例如,这样我就可以确定存储库在过去 24 小时内是否发生了更改。
我已经搜索了如何执行此操作,但我遇到的示例显示了如何创建 http 客户端,然后创建请求(以便可以添加标头),然后对其执行 do 操作。但是,由于我直接使用客户端,因此没有该选项。
go-github 的文档指出,对于条件请求:
github api 对条件请求有很好的支持,这将有助于防止您超出速率限制,并有助于加快您的应用程序速度。 go-github 不直接处理条件请求,而是设计为与缓存 http.transport 一起使用。我们建议使用 https://github.com/gregjones/httpcache 。 了解有关 github 条件请求的更多信息,请访问 https://developer.github.com/v3/#conditional-requests。
我不知道如何将其添加到我的代码中,非常感谢任何帮助。
解决方案
正如这些事情的情况一样,在发布我的问题后不久我就找到了答案。
技巧是使用 oauth2 传输中的 base 设置标头:
transport = &oauth2.transport{
source: oauth2.statictokensource(
&oauth2.token{
accesstoken: gh.tokens.github.token,
},
),
base: &transportheaders{
modifiedsince: modifiedsince,
},
}
结构体和方法如下所示:
type transportheaders struct {
modifiedsince string
}
func (t *transportheaders) roundtrip(req *http.request) (*http.response, error) {
// determine the last modified date based on the transportheader options
// do not add any headers if blank or zero
if t.modifiedsince != "" {
req.header.set("if-modified-since", t.modifiedsince)
}
return http.defaulttransport.roundtrip(req)
}
因此,通过这样做,我可以拦截对 roundtrip 的调用并添加我自己的标头。现在这意味着我可以检查资源并查看它们是否返回 304 http 状态代码。例如:
ERRO[0001] Error retrieving repository error="GET https://api.github.com/repos/chef-partners/camsa-setup: 304 []" name=camsa-setup vcs=github
在看到这个页面后我想出了如何做到这一点 - https://github.com/rmichela/go-reddit/blob/bd882abbb7496c54dbde66d92c35ad95d4db1211/authenticator.go#L117
到这里,我们也就讲完了《设置 Go-Github 和 http.Transport 的 HTTP 请求头部的方法是什么?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
