當前位置: 首頁>>代碼示例>>Golang>>正文


Golang google.ConfigFromJSON函數代碼示例

本文整理匯總了Golang中golang.org/x/oauth2/google.ConfigFromJSON函數的典型用法代碼示例。如果您正苦於以下問題:Golang ConfigFromJSON函數的具體用法?Golang ConfigFromJSON怎麽用?Golang ConfigFromJSON使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ConfigFromJSON函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: NewGDrive

func NewGDrive() *GDrive {
	var err error

	usr, err := user.Current()
	if err != nil {
		return nil
	}

	tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
	os.MkdirAll(tokenCacheDir, 0700)
	tokenCacheFile := filepath.Join(tokenCacheDir,
		url.QueryEscape("drive-go-quickstart.json"))

	b, err := ioutil.ReadFile("gdrive_client_secret.json")
	if err != nil {
		logError.Printf("Unable to read client secret file: %v", err)
		return nil
	}

	cfg, err := google.ConfigFromJSON(b, drive.DriveScope)
	if err != nil {
		logError.Printf("Unable to parse client secret file to config: %v", err)
		return nil
	}

	return &GDrive{
		clientSecret: "gdrive_client_secret.json",
		cacheFile:    tokenCacheFile,
		config:       cfg,
	}
}
開發者ID:mchoube,項目名稱:gHorcrux,代碼行數:31,代碼來源:gdrive.go

示例2: CreateGmailConfig

// CreateGmailConfig returns OAuth 2.0 config.
func CreateGmailConfig() (*oauth2.Config, error) {
	b, err := readClient()
	if err != nil {
		return nil, err
	}
	return google.ConfigFromJSON(b, gmail.GmailComposeScope, gmail.GmailModifyScope)
}
開發者ID:yyoshiki41,項目名稱:go-gmail-drafts,代碼行數:8,代碼來源:load_config.go

示例3: main

func main() {
	ctx := context.Background()

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := drive.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}

	r, err := srv.Files.List().PageSize(100).
		Fields("nextPageToken, files(id, name)").Do()
	if err != nil {
		log.Fatalf("Unable to retrieve files.", err)
	}

	fmt.Println("Files:")
	if len(r.Files) > 0 {
		for _, i := range r.Files {
			fmt.Printf("%s (%s)\n", i.Name, i.Id)
		}
	} else {
		fmt.Print("No files found.")
	}

}
開發者ID:masterhilli,項目名稱:goGoogleDrive,代碼行數:35,代碼來源:quickstart.go

示例4: InstalledAppClient

// InstalledAppClient creates an oauth authenticated client for an installed
// app based on the credentials from the developer console from an
// account labeled 'Client ID for native application'.
// cacheFilePath is the path to where the token should be cached,
// configFilePath is the path to the config file downloaded from GCE and
// scopes is the list of desired oauth2 scopes.
// If transport is nil, the default transport will be used.
// If the cache file does not contain a token the oauth2 flow will be trigger.
func InstalledAppClient(cacheFilePath, configFilePath string, transport http.RoundTripper, scopes ...string) (*http.Client, error) {
	jsonKey, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, err
	}

	config, err := google.ConfigFromJSON(jsonKey, scopes...)
	if err != nil {
		return nil, err
	}

	tokenSource, err := newCachingTokenSource(cacheFilePath, oauth2.NoContext, config)
	if err != nil {
		return nil, err
	}

	client := &http.Client{
		Transport: &oauth2.Transport{
			Source: tokenSource,
			Base:   transport,
		},
		Timeout: util.REQUEST_TIMEOUT,
	}

	return client, nil
}
開發者ID:kleopatra999,項目名稱:skia-buildbot,代碼行數:34,代碼來源:auth.go

示例5: getFilesFromGDrive

func getFilesFromGDrive() {
	ctx := context.Background()

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := gdrive.GetClient(ctx, config)

	srv, err := drive.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}

	r, err := srv.Files.List().MaxResults(10).Do()
	if err != nil {
		log.Fatalf("Unable to retrieve files.", err)
	}

	fmt.Println("Files:")
	if len(r.Items) > 0 {
		for _, i := range r.Items {
			fmt.Printf("%s (%s)\n", i.Title, i.Id)
		}
	} else {
		fmt.Print("No files found.")
	}

}
開發者ID:pandreyn,項目名稱:go-grive,代碼行數:34,代碼來源:quickstart.go

示例6: InitFromMetadataOrJSON

// InitFromMetadataOrJSON must be called before any other login methods.
//
// InitFromMetadataOrJSON will eventually replace all instances of Init, at
// which point it will be renamed back to Init().
//
// The function first tries to load the cookie salt, client id, and client
// secret from GCE project level metadata. If that fails it looks for a
// "client_secret.json" file in the current directory to extract the client id
// and client secret from. If both of those fail then it returns an error.
//
// The authWhiteList is the space separated list of domains and email addresses
// that are allowed to log in. The authWhiteList will be overwritten from
// GCE instance level metadata if present.
func InitFromMetadataOrJSON(redirectURL, scopes string, authWhiteList string) error {
	cookieSalt, clientID, clientSecret := tryLoadingFromMetadata()
	if clientID == "" {
		b, err := ioutil.ReadFile("client_secret.json")
		if err != nil {
			return fmt.Errorf("Failed to read from metadata and from client_secret.json file: %s", err)
		}
		config, err := google.ConfigFromJSON(b)
		if err != nil {
			return fmt.Errorf("Failed to read from metadata and decode client_secret.json file: %s", err)
		}
		clientID = config.ClientID
		clientSecret = config.ClientSecret
	}
	secureCookie = securecookie.New([]byte(cookieSalt), nil)
	oauthConfig.ClientId = clientID
	oauthConfig.ClientSecret = clientSecret
	oauthConfig.RedirectURL = redirectURL
	oauthConfig.Scope = scopes
	// We allow for meta data to not be present.
	whiteList, err := metadata.Get(metadata.AUTH_WHITE_LIST)
	if err != nil {
		glog.Infof("Failed to retrieve auth whitelist from instance meta data: %s", err)
	} else {
		authWhiteList = whiteList
	}
	activeDomainWhiteList, activeEmailWhiteList = splitAuthWhiteList(authWhiteList)
	return nil
}
開發者ID:saltmueller,項目名稱:skia-buildbot,代碼行數:42,代碼來源:login.go

示例7: uploadfile

func uploadfile(filename string) {
	ctx := context.Background()

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, drive.DriveScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)
	svn, err := drive.New(client)
	fmt.Printf("Svn type is %T\n", svn)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}
	m, err := os.Open(filename)
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)

	}
	//f := &drive.File{Title: filename}
	fmt.Printf("\nHi\n")
	r, err := svn.Files.Insert(&drive.File{Title: filename}).Media(m).Do()
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)
	}
	defer m.Close()
	fmt.Printf("\nBye\n %T", r)

}
開發者ID:YogeshNain,項目名稱:room,代碼行數:33,代碼來源:cnc_service.go

示例8: runGoogle

func (c *Cal2Command) runGoogle(args []string) int {
	ctx, _ := context.WithTimeout(context.Background(), 1*time.Minute)
	config, err := google.ConfigFromJSON([]byte(clientSecret), calendar.CalendarScope)
	if err != nil {
		c.UI.Error(fmt.Sprintf("unable to parse client secrete file to config: %v", err))
		return failure
	}

	u, err := stringInput(c.UI, "Username:")
	if err != nil {
		c.UI.Error(err.Error())
		return failure
	}

	client := getClient(ctx, config, u)
	srv, err := calendar.New(client)
	if err != nil {
		c.UI.Error(fmt.Sprintf("unable to retrieve calendar client %v", err))
		return failure
	}
	events, err := srv.Events.List("primary").
		ShowDeleted(false).
		SingleEvents(true).
		TimeMin(time.Now().AddDate(0, -1, 0).Format(time.RFC3339)).
		OrderBy("startTime").Do()
	if err != nil {
		c.UI.Error(fmt.Sprintf("unable to retrieve user events: $v", err))
		return failure
	}

	n := 0
	recurring := map[string]bool{}
	for _, e := range events.Items {
		if e.RecurringEventId != "" {
			recurring[e.RecurringEventId] = true
			continue // don't ingest recurring instances
		}
		c.UI.Output(fmt.Sprintf("Processing: %v", e.Summary))
		_, err := ingestEvent(ctx, c.DBClient, c.UserID, e)
		if err != nil {
			c.UI.Error(err.Error())
			return failure
		}
		n++
	}
	for id := range recurring {
		e, err := srv.Events.Get("primary", id).Do()
		if err != nil {
			c.UI.Error(err.Error())
			return failure
		}
		_, err = ingestEvent(ctx, c.DBClient, c.UserID, e)
		if err != nil {
			c.UI.Error(err.Error())
			return failure
		}
	}
	return success
}
開發者ID:elos,項目名稱:elos,代碼行數:59,代碼來源:cal2.go

示例9: createConfig

func (yt *YouTube) createConfig() error {
	b, err := ioutil.ReadFile(yt.configFilename)
	if err != nil {
		return err
	}

	yt.config, err = google.ConfigFromJSON(b, "https://www.googleapis.com/auth/youtube")
	return err
}
開發者ID:iopred,項目名稱:bruxism,代碼行數:9,代碼來源:youtube.go

示例10: form

func form(c web.C, w http.ResponseWriter, r *http.Request) {

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	config, err := google.ConfigFromJSON(b,
		drive.DriveMetadataReadonlyScope,
		drive.DriveFileScope,
		plus.UserinfoProfileScope)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	config.RedirectURL = redirectUrl

	ctx := context.Background()

	authToken := c.Env["access-token"].(oauth2.Token)

	plusClient := config.Client(ctx, &authToken)

	plusService, err := plus.New(plusClient)

	user, err := plusService.People.Get("me").Do()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	templateData := make(map[string]interface{})
	templateData["Image"] = user.Image.Url
	templateData["Name"] = user.DisplayName

	session, err := store.Get(r, "p2drive")
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	if flashes := session.Flashes("error"); len(flashes) > 0 {
		templateData["ErrorFlash"] = flashes[0]
	}

	if flashes := session.Flashes("success"); len(flashes) > 0 {
		templateData["SuccessFlash"] = flashes[0]
	}

	session.Save(r, w)

	if err := templates.Render(w, "projects-param2drive-form.html", templateData); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

}
開發者ID:tayste5000,項目名稱:tstevens,代碼行數:56,代碼來源:routes.go

示例11: GetConfig

func GetConfig() *oauth2.Config {
	b, err := ioutil.ReadFile("client_id.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}
	config, err := google.ConfigFromJSON(b, gmail.GmailModifyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	return config
}
開發者ID:chelaru-artur,項目名稱:goGmailClient,代碼行數:11,代碼來源:oauth.go

示例12: GoogleAuthConfig

func GoogleAuthConfig(keyPath string, debug bool) *oauth2.Config {
	jsonKey, err := ioutil.ReadFile(keyPath)
	if err != nil {
		log.Fatal(err)
	}
	conf, _ := google.ConfigFromJSON(jsonKey, "profile")
	if debug {
		conf.RedirectURL = "http://localhost:8080/auth/google/callback"
	}
	return conf
}
開發者ID:hi-trust,項目名稱:friendfeed,代碼行數:11,代碼來源:auth.go

示例13: main

func main() {

	client_secret_file := flag.String("client_secret_file", "", "Full Path of Client Secret File")
	gDrive_folder_id := flag.String("gDrive_folder_id", "", "Folder ID of Google Drive")
	backup_package_file := flag.String("backup_file", "", "Full Paht of backup file")

	flag.Parse()

	if *client_secret_file == "" || *gDrive_folder_id == "" || *backup_package_file == "" {
		fmt.Println("Please Input all arguments")
		os.Exit(-1)
	} else {

		ctx := context.Background()

		b, err := ioutil.ReadFile(*client_secret_file)
		if err != nil {
			log.Fatalf("Unable to read client secret file: %v", err)
		}

		config, err := google.ConfigFromJSON(b, drive.DriveScope)
		if err != nil {
			log.Fatalf("Unable to parse client secret file to config: %v", err)
		}

		client := getClient(ctx, config)

		srv, err := drive.New(client)
		if err != nil {
			log.Fatalf("Unable to create Drive service: %v", err)
		}

		fmt.Println("Client Secret File -> ", *client_secret_file)
		fmt.Println("Google Driver Folder ID -> ", *gDrive_folder_id)
		fmt.Println("Backup File Name -> ", *backup_package_file)

		goFile, err := os.Open(*backup_package_file)
		uploadfiles := new(drive.File)
		p := &drive.ParentReference{Id: *gDrive_folder_id}
		uploadfiles.Parents = []*drive.ParentReference{p}

		currentTime := time.Now()

		uploadfiles.Title = fmt.Sprintf("%04d%02d%02d-%02d%02d.tar.bz2", currentTime.Year(), currentTime.Month(), currentTime.Day(), currentTime.Hour(), currentTime.Minute())

		r, err := srv.Files.Insert(uploadfiles).Media(goFile).Do()

		if err != nil {
			log.Fatalf("Unable to retrieve files.", err)
		}

		fmt.Println("\n\nDownload URL = ", r.DownloadUrl, " \n File ID = ", r.Id, "\n File Name = ", r.OriginalFilename)
	}
}
開發者ID:luyaotsung,項目名稱:GD_Backup_GoLang,代碼行數:54,代碼來源:backup.go

示例14: initGoogleCalendarApi

func initGoogleCalendarApi() {
	b, err := ioutil.ReadFile("/etc/sac/google_api_secret.json")
	if err != nil {
		Log.Fatalf("Unable to read client secret file: %v", err)
	}

	oauthConfig, err = google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		Log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	Log.Info("Read Google API oauth config.")
}
開發者ID:rugo,項目名稱:sacapi,代碼行數:12,代碼來源:google.go

示例15: main

func main() {
	ctx := context.Background()

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := gmail.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve gmail Client %v", err)
	}

	user := "me"
	r, err := srv.Users.Labels.List(user).Do()
	if err != nil {
		log.Fatalf("Unable to retrieve labels. %v", err)
	}
	if len(r.Labels) > 0 {
		fmt.Print("Labels:\n")
		for _, l := range r.Labels {
			fmt.Printf("- %s\n", l.Name)
		}
	} else {
		fmt.Print("No labels found.")
	}

	msgsCall := srv.Users.Messages.List(user)
	msgsCall.MaxResults(1)
	msgs, er := msgsCall.Do()
	if er != nil {
		log.Fatalf("Unable to retrieve messages. %v", er)
	}

	if len(msgs.Messages) > 0 {
		var wg sync.WaitGroup
		fmt.Print("Messages:\n")
		for _, m := range msgs.Messages {
			wg.Add(1)
			go readAndRespond(user, srv, m, &wg)
		}
		wg.Wait()
	} else {
		fmt.Print("No messages found.")
	}
}
開發者ID:akkakks,項目名稱:gmail-autoresponder,代碼行數:52,代碼來源:quickstart.go


注:本文中的golang.org/x/oauth2/google.ConfigFromJSON函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。