使用Google Translate API使用Golang转换文本
我正在尝试在本地创建一个项目,以将文本转换为英语。以下是我尝试过的,但是我不断获得连接时间
错误。
client.go
文件:
package main
import (
"context"
"fmt"
"os"
translate "cloud.google.com/go/translate/apiv3"
"google.golang.org/api/option"
translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)
const (
basePath = "C:/Users/Username/go/src/abc/test-translate"
projectID = "dotted-medley-352703"
)
func translateText(text string) (string, error) {
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", basePath +"/key.json")
ctx := context.Background()
client, err := translate.NewTranslationClient(ctx, option.WithCredentialsFile(basePath + "/key.json"))
if err != nil {
return "", fmt.Errorf("Error creating client %s", err)
}
defer client.Close()
req1 := &translatepb.TranslateTextRequest{
Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
SourceLanguageCode: "de",
TargetLanguageCode: "en-us",
MimeType: "text/plain",
Contents: []string{text},
}
//tctx, _ := context.WithTimeout(ctx, time.Second*5)
resp1, err := client.TranslateText(ctx, req1)
if err != nil {
return "", fmt.Errorf("TranslateText: %v", err)
}
// Display the translation for each input text provided
for _, translation := range resp1.GetTranslations() {
fmt.Printf("Translated text: %v\n", translation.GetTranslatedText())
}
return "", nil
}
func main() {
translatedText, err := translateText("Hallo Welt")
if err != nil {
panic(err)
}
fmt.Println(translatedText)
}
我的凭据文件key.json
放置在同一目录中:
{
"type": "service_account",
"project_id": "dotted-medley-352703",
"private_key_id": "2b731ce97*****64c449aeb0b15959aa311f35cf",
"private_key": "-----BEGIN PRIVATE KEY-----/Ft780h3uyhYEnZA\nMgMvSYYIwoSda+kR******wVpNiTblablabla1JEwg01yAoYfnponFnFt0LovhxJfAlOrF1BMO7bfBL\n6ZwynluhxFrWulAgUDeiFA==\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "1177601935***3373",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"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/abc%40dotted-medley-352703.iam.gserviceaccount.com"
}
运行Go Run Client.go
:
panic: TranslateText: rpc error: code = Unavailable desc = connection error: desc = "transport: Error while dialing dial tcp 203.208.39.193:443: i/o timeout"
goroutine 1 [running]:
main.main()
C:/Users/Username/go/src/abc/test-translate/client.go:56 +0x85
exit status 2
I am trying to create a project locally to convert texts to english. Below is what I have tried, but I keep getting a connection timed out
error.
client.go
file:
package main
import (
"context"
"fmt"
"os"
translate "cloud.google.com/go/translate/apiv3"
"google.golang.org/api/option"
translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)
const (
basePath = "C:/Users/Username/go/src/abc/test-translate"
projectID = "dotted-medley-352703"
)
func translateText(text string) (string, error) {
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", basePath +"/key.json")
ctx := context.Background()
client, err := translate.NewTranslationClient(ctx, option.WithCredentialsFile(basePath + "/key.json"))
if err != nil {
return "", fmt.Errorf("Error creating client %s", err)
}
defer client.Close()
req1 := &translatepb.TranslateTextRequest{
Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
SourceLanguageCode: "de",
TargetLanguageCode: "en-us",
MimeType: "text/plain",
Contents: []string{text},
}
//tctx, _ := context.WithTimeout(ctx, time.Second*5)
resp1, err := client.TranslateText(ctx, req1)
if err != nil {
return "", fmt.Errorf("TranslateText: %v", err)
}
// Display the translation for each input text provided
for _, translation := range resp1.GetTranslations() {
fmt.Printf("Translated text: %v\n", translation.GetTranslatedText())
}
return "", nil
}
func main() {
translatedText, err := translateText("Hallo Welt")
if err != nil {
panic(err)
}
fmt.Println(translatedText)
}
My credentials file key.json
placed in the same directory:
{
"type": "service_account",
"project_id": "dotted-medley-352703",
"private_key_id": "2b731ce97*****64c449aeb0b15959aa311f35cf",
"private_key": "-----BEGIN PRIVATE KEY-----/Ft780h3uyhYEnZA\nMgMvSYYIwoSda+kR******wVpNiTblablabla1JEwg01yAoYfnponFnFt0LovhxJfAlOrF1BMO7bfBL\n6ZwynluhxFrWulAgUDeiFA==\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "1177601935***3373",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"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/abc%40dotted-medley-352703.iam.gserviceaccount.com"
}
Error received when running go run client.go
:
panic: TranslateText: rpc error: code = Unavailable desc = connection error: desc = "transport: Error while dialing dial tcp 203.208.39.193:443: i/o timeout"
goroutine 1 [running]:
main.main()
C:/Users/Username/go/src/abc/test-translate/client.go:56 +0x85
exit status 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论