LoginSignup
2
2

More than 5 years have passed since last update.

GAE/Goでanacondaを利用した認証

Posted at

GAE/Goにてanacondaを利用した際にトークンの取得でハマったのでその際のメモ


使用ライブラリの導入

go get "github.com/ChimeraCoder/anaconda"
go get "github.com/garyburd/go-oauth/oauth"
go get "google.golang.org/appengine"

importとかはみんな勝手にやってもらってるよね?


呼び出し元ハンドラ設定

ルーティングやTwitterの設定などは割愛
consumerKey,consumerSecretは適時自身のものと読み替えてください。

GAEではそのままのhttp clientでは怒られるので
http.DefaultClient.Transport = &urlfetch.Transport{Context: ctx}の記述が必要っぽい

var credential *oauth.Credentials

func GetRequestTokenHandler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)
    http.DefaultClient.Transport = &urlfetch.Transport{Context: ctx}

    anaconda.SetConsumerKey("consumerKey")
    anaconda.SetConsumerSecret("consumerSecret")

    url, tmpCred, err := anaconda.AuthorizationURL("GetAccessTokenHandlerが呼ばれるURL")
    if err != nil {
        return
    }
    credential = tmpCred
    http.Redirect(w, r, url, http.StatusFound)
}

コールバック先のハンドラ

こちらもhttp.DefaultClient.Transport = &urlfetch.Transport{Context: ctx}を記述を忘れずに

func GetAccessTokenHandler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)
    http.DefaultClient.Transport = &urlfetch.Transport{Context: ctx}

    c, _, err := anaconda.GetCredentials(credential, r.URL.Query().Get("oauth_verifier"))
    if err != nil {
        return
    }
    api := anaconda.NewTwitterApi(c.Token, c.Secret)
    // TEST POST
    api.PostTweet("test tweet", nil)
}

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2