Google Cloud "translate.NewClient: dialing: google: could not find default credentials"

huangapple go评论87阅读模式
英文:

Google Cloud "translate.NewClient: dialing: google: could not find default credentials"

问题

我正在尝试在Windows上(我的电脑)使用Google Translate API。我遇到了默认凭据的问题。

错误:**translate.NewClient: dialing: google: could not find default credentials.

我在Google Cloud中有足够的余额。

我已经启动了Translate API(API已启用)。

我添加了*$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"*。

以下是您提供的代码的翻译:

package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/storage"
	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
)

func translateTextWithModel(targetLanguage, text, model string) (string, error) {
	// targetLanguage := "ja"
	// text := "The Go Gopher is cute"
	// model := "nmt"

	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", fmt.Errorf("language.Parse: %v", err)
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return "", fmt.Errorf("translate.NewClient: %v", err)
	}
	defer client.Close()

	resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
		Model: model, // Either "nmt" or "base".
	})
	if err != nil {
		return "", fmt.Errorf("Translate: %v", err)
	}
	if len(resp) == 0 {
		return "", nil
	}
	return resp[0].Text, nil
}

func main() {
	Json_path := "C:/Users/Mels/Documents/GoogleTools/cred-9dfos6bb49f.json"
	ProjectID := "cred"
	fmt.Println("RUNNING...")
	explicit(Json_path, ProjectID)
	fmt.Println(translateTextWithModel("ja", "Hello World", "nmt"))
}

// explicit reads credentials from the specified path.
func explicit(jsonPath, projectID string) {
	ctx := context.Background()
	client, err := storage.NewClient(ctx, option.WithCredentialsFile(jsonPath))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	fmt.Println("Buckets:")
	it := client.Buckets(ctx, projectID)
	for {
		battrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(battrs.Name)
	}
}

JSON文件:

{
  "type": "service_account",
  "project_id": "xxxxxxx",
  "private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "private_key": "-----BEGIN PRIVATE KEY-----XXXXXXXX-----END PRIVATE KEY-----\n",
  "client_email": "xxxxxx@xxxxxx.iam.gserviceaccount.com",
  "client_id": "11111111111",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx%xxxxxxx.iam.gserviceaccount.com"
}

希望这可以帮助到您!

英文:

I am trying to use Google Translate API on Windows(my own computer). I have an issue with default credentials.
Error: **translate.NewClient: dialing: google: could not find default credentials.

I have enough balance in google cloud.

I started Translate API. (API Enabled)

I added $env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

package main
import (
"context"
"fmt"
"log"
"cloud.google.com/go/storage"
"cloud.google.com/go/translate"
"golang.org/x/text/language"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
func translateTextWithModel(targetLanguage, text, model string) (string, error) {
// targetLanguage := "ja"
// text := "The Go Gopher is cute"
// model := "nmt"
ctx := context.Background()
lang, err := language.Parse(targetLanguage)
if err != nil {
return "", fmt.Errorf("language.Parse: %v", err)
}
client, err := translate.NewClient(ctx)
if err != nil {
return "", fmt.Errorf("translate.NewClient: %v", err)
}
defer client.Close()
resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
Model: model, // Either "nmt" or "base".
})
if err != nil {
return "", fmt.Errorf("Translate: %v", err)
}
if len(resp) == 0 {
return "", nil
}
return resp[0].Text, nil
}
func main() {
Json_path := "C:/Users/Mels/Documents/GoogleTools/cred-9dfos6bb49f.json"
ProjectID := "cred"
fmt.Println("RUNNING...")
explicit(Json_path, ProjectID)
fmt.Println(translateTextWithModel("ja", "Hello World", "nmt"))
}
// explicit reads credentials from the specified path.
func explicit(jsonPath, projectID string) {
ctx := context.Background()
client, err := storage.NewClient(ctx, option.WithCredentialsFile(jsonPath))
if err != nil {
log.Fatal(err)
}
defer client.Close()
fmt.Println("Buckets:")
it := client.Buckets(ctx, projectID)
for {
battrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(battrs.Name)
}
}

JSON File

{
"type": "service_account",
"project_id": "xxxxxxx",
"private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----XXXXXXXX-----END PRIVATE KEY-----\n",
"client_email": "xxxxxx@xxxxxx.iam.gserviceaccount.com",
"client_id": "11111111111",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx%xxxxxxx.iam.gserviceaccount.com"
}

答案1

得分: 1

如果库找不到默认凭据,那么你可以尝试使用凭据路径创建一个客户端。

即使这可能不是最好的选择(尽管我更喜欢它而不是环境变量),但它将帮助你更好地诊断问题。

为了使用凭据文件路径创建客户端,你需要导入google.golang.org/api/option,并使用WithCredentialsFile选项创建客户端。注意文档中提到的客户端可以使用附加选项创建:

func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error)

以下是一个更完整的示例,展示如何使用选项创建客户端(根据需要将所需部分应用到你的当前代码中):

package main
import (
"cloud.google.com/go/translate"
"context"
"google.golang.org/api/option"
)
func main() {
ctx := context.Background()
client, err := translate.NewClient(ctx, option.WithCredentialsFile("/path/to/your/file"))
if err != nil {
// TODO: 处理错误。
}
// 使用客户端。
// 完成后关闭客户端。
if err := client.Close(); err != nil {
// TODO: 处理错误。
}
}

(这只是文档中示例的副本,包含了额外的选项。)

英文:

If the library can't find the default credentials, then you can try to create a client with the credentials path.

Even if this might not be the best option for you (although I prefer it to the env variable), it'll help you diagnose the issue a little better.

In order to create the client with a path to the credentials file, you need to import google.golang.org/api/option, and create the client with the WithCredentialsFile option. Note in the docs that the client can be created with additional options:

func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error)

A somewhat more complete example on how to create a client with options would be the following (apply the required parts to your current code as needed):

package main
import (
"cloud.google.com/go/translate"
"context"
"google.golang.org/api/option"
)
func main() {
ctx := context.Background()
client, err := translate.NewClient(ctx, option.WithCredentialsFile("/path/to/your/file"))
if err != nil {
// TODO: handle error.
}
// Use the client.
// Close the client when finished.
if err := client.Close(); err != nil {
// TODO: handle error.
}
}

(This is just a copy of the example in the docs with the additional option included.)

答案2

得分: 1

我解决了这个问题。我下载了"google cloud shell SDK"并使用了"gcloud auth application-default login"代码。SDK提供了一个JSON文件,我用新的JSON文件替换了它。

我不建议使用cloud.google.com/translate/docs/setup指南。直接使用Google Cloud SDK。

英文:

I solved the issue. I downloaded "google cloud shell SDK" and I used "gcloud auth application-default login" code. SDK provides a JSON file and I replaced it with new JSON file.

I do not recommend cloud.google.com/translate/docs/setup instructions. Direct use Google cloud SDK.

huangapple
  • 本文由 发表于 2021年7月9日 21:34:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/68317718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定