go-dette/translator.go

70 lines
1.6 KiB
Go
Raw Normal View History

2023-06-16 17:00:50 +03:00
package main
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"os"
)
type Translator struct {
Key string
FolderID string
}
func InitTranslator() *Translator {
return &Translator{
Key: os.Getenv("YA_KEY"),
FolderID: os.Getenv("YA_FOLDER"),
}
}
type TranslateBody struct {
FolderID string `json:"folderId"`
Texts []string `json:"texts"`
TargetLang string `json:"targetLanguageCode"`
}
type Translation struct {
Text string `json:"text"`
}
type TranslateResponse struct {
Translations []Translation `json:"translations"`
}
func (t *Translator) Translate(lang string, texts ...string) ([]string, error) {
requestURL := "https://translate.api.cloud.yandex.net/translate/v2/translate"
translateBody := TranslateBody{
FolderID: t.FolderID,
Texts: texts,
TargetLang: lang,
}
body, err := json.Marshal(translateBody)
if err != nil {
return nil, errors.Join(errors.New("can't marshal translation body"), err)
}
req, _ := http.NewRequest(http.MethodPost, requestURL, bytes.NewBuffer(body))
req.Header.Set("Authorization", "Api-Key "+t.Key)
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Join(errors.New("can't access translate api"), err)
}
defer res.Body.Close()
response, _ := io.ReadAll(res.Body)
var translations TranslateResponse
err = json.Unmarshal(response, &translations)
if err != nil {
return nil, errors.Join(errors.New("can't unmarshal translate response"), err)
}
results := []string{}
for _, tr := range translations.Translations {
results = append(results, tr.Text)
}
return results, nil
}