[英]How can I set HTTP request headers when using Go-Github and an http.Transport?
我正在编写一个应用程序,它使用 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
header。 这样我就可以计算出回购在过去 24 小时内是否发生了变化。
我已经搜索了如何执行此操作,但我遇到的示例显示了如何创建 HTTP 客户端,然后创建请求(因此可以添加标头),然后对其执行Do
操作。 但是,当我直接使用客户端时,我没有该选项。
go-github
的文档指出,对于条件请求:
GitHub API 对条件请求有很好的支持,这将有助于防止您超过速率限制,并有助于加快您的应用程序。 go-github 不直接处理条件请求,而是设计用于缓存 http.Transport。 为此,我们建议使用https://github.com/gregjones/httpcache 。
在https://developer.github.com/v3/#conditional-requests了解有关 GitHub 条件请求的更多信息。
我不知道如何在我的代码中添加它,非常感谢任何帮助。
就像这些事情一样,在发布我的问题后不久,我找到了答案。
诀窍是使用 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 的调用并添加我自己的 header。 这意味着我现在可以检查资源并查看它们是否返回 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.