本文整理匯總了Golang中github.com/dghubble/ctxh.ContextHandlerFunc函數的典型用法代碼示例。如果您正苦於以下問題:Golang ContextHandlerFunc函數的具體用法?Golang ContextHandlerFunc怎麽用?Golang ContextHandlerFunc使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ContextHandlerFunc函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestGoogleHandler
func TestGoogleHandler(t *testing.T) {
jsonData := `{"id": "900913", "name": "Ben Bitdiddle"}`
expectedUser := &google.Userinfoplus{Id: "900913", Name: "Ben Bitdiddle"}
proxyClient, server := newGoogleTestServer(jsonData)
defer server.Close()
// oauth2 Client will use the proxy client's base Transport
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient)
anyToken := &oauth2.Token{AccessToken: "any-token"}
ctx = oauth2Login.WithToken(ctx, anyToken)
config := &oauth2.Config{}
success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
googleUser, err := UserFromContext(ctx)
assert.Nil(t, err)
// assert required fields; Userinfoplus contains other raw response info
assert.Equal(t, expectedUser.Id, googleUser.Id)
assert.Equal(t, expectedUser.Id, googleUser.Id)
fmt.Fprintf(w, "success handler called")
}
failure := testutils.AssertFailureNotCalled(t)
// GoogleHandler assert that:
// - Token is read from the ctx and passed to the Google API
// - google Userinfoplus is obtained from the Google API
// - success handler is called
// - google Userinfoplus is added to the ctx of the success handler
googleHandler := googleHandler(config, ctxh.ContextHandlerFunc(success), failure)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
googleHandler.ServeHTTP(ctx, w, req)
assert.Equal(t, "success handler called", w.Body.String())
}
示例2: TestWebHandler
func TestWebHandler(t *testing.T) {
proxyClient, _, server := newDigitsTestServer(testAccountJSON)
defer server.Close()
config := &Config{
ConsumerKey: testConsumerKey,
Client: proxyClient,
}
success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
account, err := AccountFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, testDigitsToken, account.AccessToken.Token)
assert.Equal(t, testDigitsSecret, account.AccessToken.Secret)
assert.Equal(t, "0123456789", account.PhoneNumber)
endpoint, header, err := EchoFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, testAccountEndpoint, endpoint)
assert.Equal(t, testAccountRequestHeader, header)
}
handler := LoginHandler(config, ctxh.ContextHandlerFunc(success), testutils.AssertFailureNotCalled(t))
ts := httptest.NewServer(ctxh.NewHandler(handler))
// POST OAuth Echo to server under test
resp, err := http.PostForm(ts.URL, url.Values{accountEndpointField: {testAccountEndpoint}, accountRequestHeaderField: {testAccountRequestHeader}})
assert.Nil(t, err)
if assert.NotNil(t, resp) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
}
示例3: TestCallbackHandler_ExchangeError
func TestCallbackHandler_ExchangeError(t *testing.T) {
_, server := testutils.NewErrorServer("OAuth2 Service Down", http.StatusInternalServerError)
defer server.Close()
config := &oauth2.Config{
Endpoint: oauth2.Endpoint{
TokenURL: server.URL,
},
}
success := testutils.AssertSuccessNotCalled(t)
failure := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
err := gologin.ErrorFromContext(ctx)
if assert.NotNil(t, err) {
// error from golang.org/x/oauth2 config.Exchange as provider is down
assert.True(t, strings.HasPrefix(err.Error(), "oauth2: cannot fetch token"))
}
fmt.Fprintf(w, "failure handler called")
}
// CallbackHandler cannot exchange for an Access Token, assert that:
// - failure handler is called
// - error with the reason the exchange failed is added to the ctx
callbackHandler := CallbackHandler(config, success, ctxh.ContextHandlerFunc(failure))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/?code=any_code&state=d4e5f6", nil)
ctx := WithState(context.Background(), "d4e5f6")
callbackHandler.ServeHTTP(ctx, w, req)
assert.Equal(t, "failure handler called", w.Body.String())
}
示例4: TokenHandler
// TokenHandler receives a Digits access token/secret and calls the Digits
// accounts endpoint to get the corresponding Account. If successful, the
// access token/secret and Account are added to the ctx and the success handler
// is called. Otherwise, the failure handler is called.
func TokenHandler(config *oauth1.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
success = digitsHandler(config, success, failure)
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
ctx = gologin.WithError(ctx, fmt.Errorf("Method not allowed"))
failure.ServeHTTP(ctx, w, req)
return
}
req.ParseForm()
accessToken := req.PostForm.Get(accessTokenField)
accessSecret := req.PostForm.Get(accessTokenSecretField)
err := validateToken(accessToken, accessSecret)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = oauth1Login.WithAccessToken(ctx, accessToken, accessSecret)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例5: TestLoginHandler_RequestTokenError
func TestLoginHandler_RequestTokenError(t *testing.T) {
_, server := testutils.NewErrorServer("OAuth1 Service Down", http.StatusInternalServerError)
defer server.Close()
config := &oauth1.Config{
Endpoint: oauth1.Endpoint{
RequestTokenURL: server.URL,
},
}
success := testutils.AssertSuccessNotCalled(t)
failure := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
err := gologin.ErrorFromContext(ctx)
if assert.NotNil(t, err) {
// first validation in OAuth1 impl failed
assert.Equal(t, "oauth1: oauth_callback_confirmed was not true", err.Error())
}
fmt.Fprintf(w, "failure handler called")
}
// LoginHandler cannot get the OAuth1 request token, assert that:
// - failure handler is called
// - error is added to the ctx of the failure handler
loginHandler := LoginHandler(config, success, ctxh.ContextHandlerFunc(failure))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
loginHandler.ServeHTTP(context.Background(), w, req)
assert.Equal(t, "failure handler called", w.Body.String())
}
示例6: TestGithubHandler_ErrorGettingUser
func TestGithubHandler_ErrorGettingUser(t *testing.T) {
proxyClient, server := testutils.NewErrorServer("Github Service Down", http.StatusInternalServerError)
defer server.Close()
// oauth2 Client will use the proxy client's base Transport
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient)
anyToken := &oauth2.Token{AccessToken: "any-token"}
ctx = oauth2Login.WithToken(ctx, anyToken)
config := &oauth2.Config{}
success := testutils.AssertSuccessNotCalled(t)
failure := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
err := gologin.ErrorFromContext(ctx)
if assert.NotNil(t, err) {
assert.Equal(t, ErrUnableToGetGithubUser, err)
}
fmt.Fprintf(w, "failure handler called")
}
// GithubHandler cannot get Github User, assert that:
// - failure handler is called
// - error cannot get Github User added to the failure handler ctx
githubHandler := githubHandler(config, success, ctxh.ContextHandlerFunc(failure))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
githubHandler.ServeHTTP(ctx, w, req)
assert.Equal(t, "failure handler called", w.Body.String())
}
示例7: TestTokenHandler
func TestTokenHandler(t *testing.T) {
proxyClient, _, server := newDigitsTestServer(testAccountJSON)
defer server.Close()
// oauth1 Client will use the proxy client's base Transport
ctx := context.WithValue(context.Background(), oauth1.HTTPClient, proxyClient)
config := &oauth1.Config{}
success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
account, err := AccountFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, testDigitsToken, account.AccessToken.Token)
assert.Equal(t, testDigitsSecret, account.AccessToken.Secret)
assert.Equal(t, "0123456789", account.PhoneNumber)
accessToken, accessSecret, err := oauth1Login.AccessTokenFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, testDigitsToken, accessToken)
assert.Equal(t, testDigitsSecret, accessSecret)
}
handler := TokenHandler(config, ctxh.ContextHandlerFunc(success), testutils.AssertFailureNotCalled(t))
ts := httptest.NewServer(ctxh.NewHandlerWithContext(ctx, handler))
// POST Digits access token to server under test
resp, err := http.PostForm(ts.URL, url.Values{accessTokenField: {testDigitsToken}, accessTokenSecretField: {testDigitsSecret}})
assert.Nil(t, err)
if assert.NotNil(t, resp) {
assert.Equal(t, resp.StatusCode, http.StatusOK)
}
}
示例8: getAccountViaEcho
// getAccountViaEcho is a ContextHandler that gets the Digits Echo endpoint and
// OAuth header from the ctx and calls the endpoint to get the corresponding
// Digits Account. If successful, the Account is added to the ctx and the
// success handler is called. Otherwise, the failure handler is called.
func getAccountViaEcho(config *Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
if failure == nil {
failure = gologin.DefaultFailureHandler
}
client := config.Client
if client == nil {
client = http.DefaultClient
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
endpoint, header, err := EchoFromContext(ctx)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
// fetch the Digits Account
account, resp, err := requestAccount(client, endpoint, header)
// validate the Digits Account response
err = validateResponse(account, resp, err)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithAccount(ctx, account)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例9: LoginHandler
// LoginHandler receives a Digits OAuth Echo endpoint and OAuth header,
// validates the echo, and calls the endpoint to get the corresponding Digits
// Account. If successful, the Digits Account is added to the ctx and the
// success handler is called. Otherwise, the failure handler is called.
func LoginHandler(config *Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
success = getAccountViaEcho(config, success, failure)
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
ctx = gologin.WithError(ctx, fmt.Errorf("Method not allowed"))
failure.ServeHTTP(ctx, w, req)
return
}
req.ParseForm()
accountEndpoint := req.PostForm.Get(accountEndpointField)
accountRequestHeader := req.PostForm.Get(accountRequestHeaderField)
// validate POST'ed Digits OAuth Echo data
err := validateEcho(accountEndpoint, accountRequestHeader, config.ConsumerKey)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithEcho(ctx, accountEndpoint, accountRequestHeader)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例10: facebookHandler
// facebookHandler is a ContextHandler that gets the OAuth2 Token from the ctx
// to get the corresponding Facebook User. If successful, the user is added to
// the ctx and the success handler is called. Otherwise, the failure handler
// is called.
func facebookHandler(config *oauth2.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
token, err := oauth2Login.TokenFromContext(ctx)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
httpClient := config.Client(ctx, token)
facebookService := newClient(httpClient)
user, resp, err := facebookService.Me()
err = validateResponse(user, resp, err)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithUser(ctx, user)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例11: googleHandler
// googleHandler is a ContextHandler that gets the OAuth2 Token from the ctx
// to get the corresponding Google Userinfoplus. If successful, the user info
// is added to the ctx and the success handler is called. Otherwise, the
// failure handler is called.
func googleHandler(config *oauth2.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
token, err := oauth2Login.TokenFromContext(ctx)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
httpClient := config.Client(ctx, token)
googleService, err := google.New(httpClient)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
userInfoPlus, err := googleService.Userinfo.Get().Do()
err = validateResponse(userInfoPlus, err)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithUser(ctx, userInfoPlus)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例12: TestGithubHandler
func TestGithubHandler(t *testing.T) {
jsonData := `{"id": 917408, "name": "Alyssa Hacker"}`
expectedUser := &github.User{ID: github.Int(917408), Name: github.String("Alyssa Hacker")}
proxyClient, server := newGithubTestServer(jsonData)
defer server.Close()
// oauth2 Client will use the proxy client's base Transport
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient)
anyToken := &oauth2.Token{AccessToken: "any-token"}
ctx = oauth2Login.WithToken(ctx, anyToken)
config := &oauth2.Config{}
success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
githubUser, err := UserFromContext(ctx)
assert.Nil(t, err)
assert.Equal(t, expectedUser, githubUser)
fmt.Fprintf(w, "success handler called")
}
failure := testutils.AssertFailureNotCalled(t)
// GithubHandler assert that:
// - Token is read from the ctx and passed to the Github API
// - github User is obtained from the Github API
// - success handler is called
// - github User is added to the ctx of the success handler
githubHandler := githubHandler(config, ctxh.ContextHandlerFunc(success), failure)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
githubHandler.ServeHTTP(ctx, w, req)
assert.Equal(t, "success handler called", w.Body.String())
}
示例13: TestCallbackHandler
func TestCallbackHandler(t *testing.T) {
expectedToken := "acces_token"
expectedSecret := "access_secret"
requestSecret := "request_secret"
data := url.Values{}
data.Add("oauth_token", expectedToken)
data.Add("oauth_token_secret", expectedSecret)
server := NewAccessTokenServer(t, data)
defer server.Close()
config := &oauth1.Config{
Endpoint: oauth1.Endpoint{
AccessTokenURL: server.URL,
},
}
success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
accessToken, accessSecret, err := AccessTokenFromContext(ctx)
assert.Equal(t, expectedToken, accessToken)
assert.Equal(t, expectedSecret, accessSecret)
assert.Nil(t, err)
fmt.Fprintf(w, "success handler called")
}
failure := testutils.AssertFailureNotCalled(t)
// CallbackHandler gets OAuth1 access token, assert that:
// - success handler is called
// - access token and secret added to the ctx of the success handler
// - failure handler is not called
callbackHandler := CallbackHandler(config, ctxh.ContextHandlerFunc(success), failure)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/?oauth_token=any_token&oauth_verifier=any_verifier", nil)
ctx := WithRequestToken(context.Background(), "", requestSecret)
callbackHandler.ServeHTTP(ctx, w, req)
assert.Equal(t, "success handler called", w.Body.String())
}
示例14: twitterHandler
// twitterHandler is a ContextHandler that gets the OAuth1 access token from
// the ctx and calls Twitter verify_credentials to get the corresponding User.
// If successful, the User is added to the ctx and the success handler is
// called. Otherwise, the failure handler is called.
func twitterHandler(config *oauth1.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
accessToken, accessSecret, err := oauth1Login.AccessTokenFromContext(ctx)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
httpClient := config.Client(ctx, oauth1.NewToken(accessToken, accessSecret))
twitterClient := twitter.NewClient(httpClient)
accountVerifyParams := &twitter.AccountVerifyParams{
IncludeEntities: twitter.Bool(false),
SkipStatus: twitter.Bool(true),
IncludeEmail: twitter.Bool(false),
}
user, resp, err := twitterClient.Accounts.VerifyCredentials(accountVerifyParams)
err = validateResponse(user, resp, err)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithUser(ctx, user)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例15: tumblrHandler
// tumblrHandler is a ContextHandler that gets the OAuth1 access token from
// the ctx and obtains the Tumblr User. If successful, the User is added to
// the ctx and the success handler is called. Otherwise, the failure handler
// is called.
func tumblrHandler(config *oauth1.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
accessToken, accessSecret, err := oauth1Login.AccessTokenFromContext(ctx)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
httpClient := config.Client(ctx, oauth1.NewToken(accessToken, accessSecret))
tumblrClient := newClient(httpClient)
user, resp, err := tumblrClient.UserInfo()
err = validateResponse(user, resp, err)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithUser(ctx, user)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}