-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
highlevel.go
54 lines (46 loc) · 1.61 KB
/
highlevel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2021 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package mock demonstrates how to use interfaces to mock interactions with
// service in tests.
package mock
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/api/option"
"google.golang.org/api/translate/v3"
)
// TranslateService is a facade of a `translate.Service`, specifically used to
// for translating text.
type TranslateService interface {
TranslateText(text, language string) (string, error)
}
// TranslateTextHighLevel translates text to the given language using the
// provided service.
func TranslateTextHighLevel(service TranslateService, text, language string) (string, error) {
return service.TranslateText(text, language)
}
type translateService struct {
svc *translate.Service
}
// NewTranslateService creates a TranslateService.
func NewTranslateService(ctx context.Context, opts ...option.ClientOption) TranslateService {
svc, err := translate.NewService(ctx, opts...)
if err != nil {
log.Fatalf("unable to create translate service, shutting down: %v", err)
}
return &translateService{svc}
}
func (t *translateService) TranslateText(text, language string) (string, error) {
parent := fmt.Sprintf("projects/%s/locations/global", os.Getenv("GOOGLE_CLOUD_PROJECT"))
resp, err := t.svc.Projects.Locations.TranslateText(parent, &translate.TranslateTextRequest{
TargetLanguageCode: language,
Contents: []string{text},
}).Do()
if err != nil {
return "", fmt.Errorf("unable to translate text: %v", err)
}
return resp.Translations[0].TranslatedText, nil
}