如何将 go-vcr 与 githubv4 一起使用?- 获取 httpClient 传输

查看 go-vcr 的设置


// Start our recorder

    r, err := recorder.New("fixtures/etcd")

    if err != nil {

        log.Fatal(err)

    }

    defer r.Stop() // Make sure recorder is stopped once done with it


    // Create an etcd configuration using our transport

    cfg := client.Config{

        Endpoints:               []string{"http://127.0.0.1:2379"},

        HeaderTimeoutPerRequest: time.Second,

        Transport:               r, // Inject as transport!

    }

尝试使用 githubv4 库来使用这个库似乎需要一种方法来处理 Oauth


import "golang.org/x/oauth2"


func main() {

    src := oauth2.StaticTokenSource(

        &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")},

    )

    httpClient := oauth2.NewClient(context.Background(), src)


    client := githubv4.NewClient(httpClient)

    // Use client...

}

我不确定如何将记录器“r”放入 oauth2 客户端。如果可能的话。


有人成功过吗?我试过使用“r”记录器传递一个 httpClient,但它最终显示为 401 - 看起来这个默认客户端无法执行 Oauth 舞蹈。


我想使用 GraphQL API,但如果更容易的话可以回退到 REST API,但我只是想确保这真的不可能。还有其他人成功了吗?


www说
浏览 192回答 1
1回答

长风秋雁

这个问题为我解决了这个问题。 https://github.com/dnaeon/go-vcr/issues/59下面的例子package example_testimport (    "context"    "github.com/dnaeon/go-vcr/cassette"    "github.com/dnaeon/go-vcr/recorder"    "github.com/google/go-github/v33/github"    "github.com/stretchr/testify/require"    "golang.org/x/oauth2"    "net/http"    "path"    "testing")func TestGithub(t *testing.T) {    //custom http.Transport, since github uses oauth2 authentication    ts := oauth2.StaticTokenSource(        &oauth2.Token{AccessToken: "YOUR_GITHUB_TOKEN"},    )    tr := &oauth2.Transport{        Base:  http.DefaultTransport,        Source: oauth2.ReuseTokenSource(nil, ts),    }    // Start our recorder    vcrRecorder, err := recorder.NewAsMode(path.Join("testdata", "fixtures", t.Name()), recorder.ModeRecording, tr)    require.NoError(t, err)        defer vcrRecorder.Stop() // NEWLY ADDED CODE HERE    // Filter out dynamic & sensitive data/headers    // Your test code will continue to see the real access token and    // it is redacted before the recorded interactions are saved        // =====> commenting out this section has no impact on missing recording    vcrRecorder.AddSaveFilter(func(i *cassette.Interaction) error {        delete(i.Request.Headers, "Authorization")        delete(i.Request.Headers, "User-Agent")        i.Request.Headers["Authorization"] = []string{"Basic UExBQ0VIT0xERVI6UExBQ0VIT0xERVI="} //PLACEHOLDER:PLACEHOLDER        return nil    })        // custom http.client    httpClient := &http.Client{        Transport: vcrRecorder,    }    ghClient := github.NewClient(httpClient)    // =====> actual test, should create cassettes, but does not.    _, _, err = ghClient.Users.Get(context.Background(), "")    require.NoError(t, err)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go