本文整理汇总了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,
}
}
示例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)
}
示例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.")
}
}
示例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
}
示例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.")
}
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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)
}
}
示例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
}
示例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
}
示例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)
}
}
示例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.")
}
示例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.")
}
}