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

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

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"*。

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

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "cloud.google.com/go/storage"
  7. "cloud.google.com/go/translate"
  8. "golang.org/x/text/language"
  9. "google.golang.org/api/iterator"
  10. "google.golang.org/api/option"
  11. )
  12. func translateTextWithModel(targetLanguage, text, model string) (string, error) {
  13. // targetLanguage := "ja"
  14. // text := "The Go Gopher is cute"
  15. // model := "nmt"
  16. ctx := context.Background()
  17. lang, err := language.Parse(targetLanguage)
  18. if err != nil {
  19. return "", fmt.Errorf("language.Parse: %v", err)
  20. }
  21. client, err := translate.NewClient(ctx)
  22. if err != nil {
  23. return "", fmt.Errorf("translate.NewClient: %v", err)
  24. }
  25. defer client.Close()
  26. resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
  27. Model: model, // Either "nmt" or "base".
  28. })
  29. if err != nil {
  30. return "", fmt.Errorf("Translate: %v", err)
  31. }
  32. if len(resp) == 0 {
  33. return "", nil
  34. }
  35. return resp[0].Text, nil
  36. }
  37. func main() {
  38. Json_path := "C:/Users/Mels/Documents/GoogleTools/cred-9dfos6bb49f.json"
  39. ProjectID := "cred"
  40. fmt.Println("RUNNING...")
  41. explicit(Json_path, ProjectID)
  42. fmt.Println(translateTextWithModel("ja", "Hello World", "nmt"))
  43. }
  44. // explicit reads credentials from the specified path.
  45. func explicit(jsonPath, projectID string) {
  46. ctx := context.Background()
  47. client, err := storage.NewClient(ctx, option.WithCredentialsFile(jsonPath))
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. defer client.Close()
  52. fmt.Println("Buckets:")
  53. it := client.Buckets(ctx, projectID)
  54. for {
  55. battrs, err := it.Next()
  56. if err == iterator.Done {
  57. break
  58. }
  59. if err != nil {
  60. log.Fatal(err)
  61. }
  62. fmt.Println(battrs.Name)
  63. }
  64. }

JSON文件:

  1. {
  2. "type": "service_account",
  3. "project_id": "xxxxxxx",
  4. "private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  5. "private_key": "-----BEGIN PRIVATE KEY-----XXXXXXXX-----END PRIVATE KEY-----\n",
  6. "client_email": "xxxxxx@xxxxxx.iam.gserviceaccount.com",
  7. "client_id": "11111111111",
  8. "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  9. "api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  10. "token_uri": "https://oauth2.googleapis.com/token",
  11. "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  12. "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx%xxxxxxx.iam.gserviceaccount.com"
  13. }

希望这可以帮助到您!

英文:

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"

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "cloud.google.com/go/storage"
  7. "cloud.google.com/go/translate"
  8. "golang.org/x/text/language"
  9. "google.golang.org/api/iterator"
  10. "google.golang.org/api/option"
  11. )
  12. func translateTextWithModel(targetLanguage, text, model string) (string, error) {
  13. // targetLanguage := "ja"
  14. // text := "The Go Gopher is cute"
  15. // model := "nmt"
  16. ctx := context.Background()
  17. lang, err := language.Parse(targetLanguage)
  18. if err != nil {
  19. return "", fmt.Errorf("language.Parse: %v", err)
  20. }
  21. client, err := translate.NewClient(ctx)
  22. if err != nil {
  23. return "", fmt.Errorf("translate.NewClient: %v", err)
  24. }
  25. defer client.Close()
  26. resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
  27. Model: model, // Either "nmt" or "base".
  28. })
  29. if err != nil {
  30. return "", fmt.Errorf("Translate: %v", err)
  31. }
  32. if len(resp) == 0 {
  33. return "", nil
  34. }
  35. return resp[0].Text, nil
  36. }
  37. func main() {
  38. Json_path := "C:/Users/Mels/Documents/GoogleTools/cred-9dfos6bb49f.json"
  39. ProjectID := "cred"
  40. fmt.Println("RUNNING...")
  41. explicit(Json_path, ProjectID)
  42. fmt.Println(translateTextWithModel("ja", "Hello World", "nmt"))
  43. }
  44. // explicit reads credentials from the specified path.
  45. func explicit(jsonPath, projectID string) {
  46. ctx := context.Background()
  47. client, err := storage.NewClient(ctx, option.WithCredentialsFile(jsonPath))
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. defer client.Close()
  52. fmt.Println("Buckets:")
  53. it := client.Buckets(ctx, projectID)
  54. for {
  55. battrs, err := it.Next()
  56. if err == iterator.Done {
  57. break
  58. }
  59. if err != nil {
  60. log.Fatal(err)
  61. }
  62. fmt.Println(battrs.Name)
  63. }
  64. }

JSON File

  1. {
  2. "type": "service_account",
  3. "project_id": "xxxxxxx",
  4. "private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  5. "private_key": "-----BEGIN PRIVATE KEY-----XXXXXXXX-----END PRIVATE KEY-----\n",
  6. "client_email": "xxxxxx@xxxxxx.iam.gserviceaccount.com",
  7. "client_id": "11111111111",
  8. "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  9. "api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  10. "token_uri": "https://oauth2.googleapis.com/token",
  11. "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  12. "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx%xxxxxxx.iam.gserviceaccount.com"
  13. }

答案1

得分: 1

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

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

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

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

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

  1. package main
  2. import (
  3. "cloud.google.com/go/translate"
  4. "context"
  5. "google.golang.org/api/option"
  6. )
  7. func main() {
  8. ctx := context.Background()
  9. client, err := translate.NewClient(ctx, option.WithCredentialsFile("/path/to/your/file"))
  10. if err != nil {
  11. // TODO: 处理错误。
  12. }
  13. // 使用客户端。
  14. // 完成后关闭客户端。
  15. if err := client.Close(); err != nil {
  16. // TODO: 处理错误。
  17. }
  18. }

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

英文:

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):

  1. package main
  2. import (
  3. "cloud.google.com/go/translate"
  4. "context"
  5. "google.golang.org/api/option"
  6. )
  7. func main() {
  8. ctx := context.Background()
  9. client, err := translate.NewClient(ctx, option.WithCredentialsFile("/path/to/your/file"))
  10. if err != nil {
  11. // TODO: handle error.
  12. }
  13. // Use the client.
  14. // Close the client when finished.
  15. if err := client.Close(); err != nil {
  16. // TODO: handle error.
  17. }
  18. }

(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:

确定