我无法使用以下go代码检索访问令牌

时间:2015-02-16 10:41:18

标签: go

func handler(w http.ResponseWriter, r *http.Request) {
    t := &oauth.Transport{Config: config}
    c := r.FormValue("code")
    token, err := t.Exchange(c)
    fmt.Println("token: ", token, "\nerr: ", err)
}

错误:

token:  <nil> 
err:  OAuthError: updateToken: Unexpected HTTP status 400 Bad Request

1 个答案:

答案 0 :(得分:0)

您使用的goauth2包是否已弃用?如果是这样,您可以尝试使用golang.org/x/oauth2

package main

import (
    "log"
    "net/http"

    "code.google.com/p/google-api-go-client/youtube/v3"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
)

// variables used during oauth protocol flow of authentication
var (
    code  = ""
    token = ""
)

var oauthCfg = &oauth2.Config{
    ClientID:     "...",
    ClientSecret: "...",
    RedirectURL:  "http://localhost:8888/oauth2callback",
    Scopes: []string{
        youtube.YoutubeScope, //e.g.
    },
    Endpoint: google.Endpoint,
}

func main() {

    http.HandleFunc("/", mainHander)

    http.HandleFunc("/oauth2callback", callbackHandler)

    http.ListenAndServe(":8888", nil)
}

func mainHander(w http.ResponseWriter, r *http.Request) {
    url := oauthCfg.AuthCodeURL("")

    http.Redirect(w, r, url, http.StatusFound)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
    code := r.FormValue("code")

    tok, err := oauthCfg.Exchange(oauth2.NoContext, code)

    if err != nil {
        log.Fatal(err)
    }

    log.Println(tok)
}