Convert text using Google translate API using Golang

Viewed 245

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": "abc@dotted-medley-352703.iam.gserviceaccount.com",
    "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
0 Answers
Related