使用包 "golang.org/x/oauth2" 通过 oauth2 进行身份验证

Authenticating with oauth2 using package "golang.org/x/oauth2"

我想弄清楚如何使用包 golang.org/x/oauth2 在支持 oauth2 的站点上进行身份验证。

我在下面写的代码有效,我只是好奇这是否是正确的方法,使用这个特定的库来获得 *http.Client:

func handleCallback(w http.ResponseWriter, r *http.Request) {
    state := r.FormValue("state")
    if state != oauthStateString {
        fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    code := r.FormValue("code")
    token, err := oauthConf.Exchange(oauth2.NoContext, code)
    if err != nil {
        fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    ts := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: token.AccessToken},
    )

    tc := oauth2.NewClient(oauth2.NoContext, ts) // got *http.Client

跟进:我已经使用它并对其进行了多次调整,并且可以正常工作。