本文整理汇总了Golang中code/google/com/p/goauth2/oauth.Transport类的典型用法代码示例。如果您正苦于以下问题:Golang Transport类的具体用法?Golang Transport怎么用?Golang Transport使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: initTransport
func initTransport(transport *oauth.Transport) error {
// First: check the cache.
if token, err := transport.Config.TokenCache.Token(); err == nil {
// We have a token, refresh it. The lifetime is 1h, so we always
// refresh to ensure lengthy commands do not time out.
transport.Token = token
err := transport.Refresh()
if err == nil {
return nil
}
log.Infof("token refresh failed, requesting new one")
}
// Get a new token. Pops up a browser window (hopefully).
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
authURL := transport.Config.AuthCodeURL(randState)
log.Infof("Opening auth URL in browser: %s", authURL)
log.Infof("If the URL doesn't open please open it manually and copy the code here.")
openURL(authURL)
code := getCodeFromStdin()
_, err := transport.Exchange(code)
if err != nil {
log.Infof("problem exchanging code: %v", err)
return err
}
return nil
}
示例2: VerifyClaim
// VerifyClaim checks that the printer has been claimed.
// If the printer is claimed, VerifyClaim returns no error.
// If the printer is unclaimed, VerifyClaim retruns ErrUnclaimed.
// It is possible for VerifyClaim to return other errors, such as
// in the case of network problems.
//
// A side effect of verifying that claim is that Google creates
// a synthetic account that is only useful in a future call to
// NewServer, to manage just this one printer.
// The information about that account can be retrieved
// from the Auth, Printer, and Server methods after VerifyClaim
// succeeds.
func (p *OpenPrinter) VerifyClaim() error {
if p.verify != nil {
return nil
}
var resp verifyResponse
if err := jsonRPC(&p.auth, "GET", p.register.PollingURL+p.auth.APIClientID, nil, &resp); err != nil {
return fmt.Errorf("VerifyClaim: %v", err)
}
var tr oauth.Transport
tr.Config = &oauth.Config{
ClientId: p.auth.APIClientID,
ClientSecret: p.auth.APIClientSecret,
Scope: "https://www.googleapis.com/auth/cloudprint https://www.googleapis.com/auth/googletalk",
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
RedirectURL: "oob",
}
tok, err := tr.Exchange(resp.AuthorizationCode)
if err != nil {
return fmt.Errorf("VerifyClaim: oauth exchange: %v", err)
}
p.auth.Token = *tok
p.auth.TokenUser = resp.UserEmail
p.auth.XMPPJID = resp.XMPPJID
p.verify = &resp
return nil
}
示例3: authenticate
func authenticate(transport *oauth.Transport) error {
code := make(chan string)
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
return err
}
go http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, closeMessage)
code <- r.FormValue("code") // send code to OAuth flow
listener.Close() // shut down HTTP server
}))
transport.Config.RedirectURL = fmt.Sprintf("http://%s/", listener.Addr())
url := transport.Config.AuthCodeURL("")
if err := openURL(url); err != nil {
fmt.Fprintln(os.Stderr, visitMessage)
} else {
fmt.Fprintln(os.Stderr, openedMessage)
}
fmt.Fprintf(os.Stderr, "\n%s\n\n", url)
fmt.Fprintln(os.Stderr, resumeMessage)
_, err = transport.Exchange(<-code)
return err
}
示例4: rtRoot
func rtRoot(w http.ResponseWriter, r *http.Request, args []string) error {
sess := getSession(r)
if sess == nil || sess.token == nil {
http.Redirect(w, r, "/oauth2/login", http.StatusFound)
return nil
}
t := oauth.Transport{
Config: oauthConfig,
Token: sess.token,
}
if er := t.Refresh(); er != nil {
return er
}
res, er := t.Client().Get("https://api.guildwars2.com/v2/account")
if er != nil {
return er
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, res.Body)
return nil
}
示例5: get_profile_facebook
func get_profile_facebook(transport *oauth.Transport) (Profile, error) {
resp, err := transport.Client().Get("https://graph.facebook.com/me?fields=id,name,first_name,last_name,email,username,picture.width(256).height(256)")
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("http status: %d", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
profile := &FacebookProfile{}
err = json.Unmarshal(data, &profile)
if err != nil {
return nil, err
}
profile.raw = data
return profile, nil
}
示例6: get_profile_github
func get_profile_github(transport *oauth.Transport) (Profile, error) {
resp, err := transport.Client().Get("https://api.github.com/user")
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("http status: %d", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
profile := &GithubProfile{}
err = json.Unmarshal(data, &profile)
if err != nil {
return nil, err
}
profile.raw = data
return profile, nil
}
示例7: getToken
func getToken(t *oauth.Transport) {
var c string
authURL := config.AuthCodeURL("state")
log.Printf("Open in browser: %v\n", authURL)
log.Printf("Enter verification code: ")
fmt.Scanln(&c)
_, err := t.Exchange(c)
if err != nil {
log.Fatalf("An error occurred exchanging the code: %v\n", err)
}
}
示例8: GetHttpClient
// GetHttpClient returns a http.Client which performs authenticated requests as
// the logged-in user.
func GetHttpClient(r *http.Request) *http.Client {
s, err := getSession(r)
if err != nil {
glog.Errorf("Failed to get session state; falling back to default http client.")
return &http.Client{}
}
t := oauth.Transport{
Config: oauthConfig,
Token: s.Token,
}
return t.Client()
}
示例9: fetch_all_contacts
// This function does the work of obtaining the contacts from the server
func fetch_all_contacts(transport *oauth.Transport) contacts_response {
// XXX: increase the max-results
request_url := fmt.Sprintf("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&max-results=10000")
// fmt.Println("request_url is", request_url)
resp, _ := transport.Client().Get(request_url)
defer resp.Body.Close()
var result contacts_response
err := json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
log.Fatal(err)
}
return result
}
示例10: authorize
func authorize(w http.ResponseWriter, r *http.Request, t *oauth.Transport) (*oauth.Token, error) {
//Get the code from the response
code := r.FormValue("code")
if code == "" {
// Get an authorization code from the data provider.
// ("Please ask the user if I can access this resource.")
url := config.AuthCodeURL("")
http.Redirect(w, r, url, http.StatusFound)
return nil, nil
}
// Exchange the authorization code for an access token.
// ("Here's the code you gave the user, now give me a token!")
return t.Exchange(code)
}
示例11: userData
// obtain user data from constant REQUEST_API
// UserInfo is used to Unmarshal the json response
// returns UserInfor strct for display
func userData(w http.ResponseWriter, transport *oauth.Transport, token string, ui *UserInfo) (UserInfo, error) {
url := REQUEST_API + token
resp, err := transport.Client().Get(url)
if err != nil {
http.Error(w, "api error", http.StatusInternalServerError)
return *ui, errors.New("api error")
}
defer resp.Body.Close()
d, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(d, &ui)
return *ui, nil
}
示例12: handleOAuth2Callback
func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
next := extractPath(r.URL.Query().Get("state"))
code := r.URL.Query().Get("code")
tk, err := t.Exchange(code)
if err != nil {
// Pass the error message, or allow dev to provide its own
// error handler.
http.Redirect(w, r, PathError, codeRedirect)
return
}
// Store the credentials in the session.
val, _ := json.Marshal(tk)
s.Set(keyToken, val)
http.Redirect(w, r, next, codeRedirect)
}
示例13: initializeApiService
func initializeApiService(c appengine.Context) (*api.Service, error) {
d := datastore.New(c)
token, err := d.FindToken(user.Current(c).Email)
if err != nil {
return nil, err
}
transport := oauth.Transport{
Token: &token,
Config: &cfg,
Transport: urlfetch.Client(c).Transport,
}
return api.NewFromClient(transport.Client(), token.AccessToken), nil
}
示例14: newOauthClient
func newOauthClient(storePath string) *http.Client {
config := &oauth.Config{
ClientId: ClientId,
ClientSecret: ClientSecret,
Scope: raw.ComputeScope,
AuthURL: AuthURL,
TokenURL: TokenURL,
}
token := token(storePath, config)
t := oauth.Transport{
Token: token,
Config: config,
Transport: http.DefaultTransport,
}
return t.Client()
}
示例15: hasValidToken
// Returns true if we have a valid cached token
func hasValidToken(cacheFile oauth.CacheFile, transport *oauth.Transport) bool {
// Check if we have a cached token
token, err := cacheFile.Token()
if err != nil {
return false
}
// Refresh token if its expired
if token.Expired() {
transport.Token = token
err = transport.Refresh()
if err != nil {
fmt.Println(err)
return false
}
}
return true
}