-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation.go
46 lines (36 loc) · 922 Bytes
/
translation.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
package main
import (
"errors"
"github.com/go-resty/resty/v2"
)
type TranslationAPIResponse struct {
Contents struct {
Translated string `json:"translated"`
} `json:"contents"`
}
func getTranslation(text string) (string, error) {
client := resty.New()
resp, err := client.R().
SetFormData(map[string]string{
"text": text,
}).
SetError(apiError{}).
SetResult(TranslationAPIResponse{}).
Post("https://api.funtranslations.com/translate/shakespeare.json")
if err != nil {
return "", err
}
if resp.IsError() {
err, _ := resp.Error().(*apiError)
return "", &err.Error
}
// Extract the description from the API response
data, ok := resp.Result().(*TranslationAPIResponse)
if !ok {
return "", errors.New("response was not a Translation API format")
}
if len(data.Contents.Translated) == 0 {
return "", errors.New("no translation found")
}
return data.Contents.Translated, nil
}