首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何设置http.Transport在使用Github和http.Transport时?

如何设置http.Transport在使用Github和http.Transport时?
EN

Stack Overflow用户
提问于 2019-09-30 10:53:13
回答 1查看 489关注 0票数 0

我正在编写一个应用程序,它使用GitHub API来查看GitHub orgs中的存储库。我正在使用github.com/google/go-github库。

我还使用github.com/gregjones/httpcache,以便能够进行基于令牌的身份验证,并为API调用设置条件标头。我的认证工作是这样的:

代码语言:javascript
复制
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)

但是,例如,当我使用If-Match时,我无法解决如何添加必要的client.Repositories.Get头。这是为了我可以计算出,如果回购已经改变了在过去24小时的例子。

我已经搜索了如何做到这一点,但是我遇到的例子显示了如何创建一个HTTP客户机,然后创建一个请求(这样就可以添加头部),然后对它执行一个Do操作。但是,由于我直接使用客户端,所以我没有这个选项。

go-github的文档声明了有条件请求的文档:

GitHub API对条件请求有很好的支持,这将有助于防止您通过速率限制,并帮助加快您的应用程序。github不直接处理条件请求,而是设计用于使用缓存http.Transport。为此,我们建议使用https://github.com/gregjones/httpcache

在GitHub上了解有关https://developer.github.com/v3/#conditional-requests条件请求的更多信息。

我不知道如何在我的代码中添加它,任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-30 12:04:19

就像这些事情的情况一样,在发布我的问题后不久,我找到了答案。

因此,诀窍是使用Base在Oauth2传输中设置标头:

代码语言:javascript
复制
transport = &oauth2.Transport{
    Source: oauth2.StaticTokenSource(
        &oauth2.Token{
            AccessToken: gh.tokens.GitHub.Token,
        },
    ),
    Base: &transportHeaders{
        modifiedSince: modifiedSince,
    },
}

结构和方法如下所示:

代码语言:javascript
复制
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状态代码。例如:

代码语言:javascript
复制
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之后,我想出了如何做到这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58166420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档