【问题标题】:How can I set HTTP request headers when using Go-Github and an http.Transport?使用 Go-Github 和 http.Transport 时如何设置 HTTP 请求标头?
【发布时间】:2019-09-30 10:53:13
【问题描述】:

我正在编写一个应用程序,它使用 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 标头。这样我就可以确定 repo 在过去 24 小时内是否发生了变化。

我已经搜索了如何执行此操作,但我遇到的示例显示了如何创建 HTTP 客户端,然后创建请求(因此可以添加标头),然后对其执行 Do 操作。但是,由于我直接使用客户端,所以我没有该选项。

go-github 的文档指出,对于条件请求:

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

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

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

【问题讨论】:

    标签: go go-github


    【解决方案1】:

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

    诀窍是在 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

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 2017-04-17
      • 2011-06-24
      • 2013-04-12
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多