/
deeplx.go
77 lines (61 loc) · 1.49 KB
/
deeplx.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package deeplx
import (
"encoding/json"
"errors"
"github.com/abadojack/whatlanggo"
"github.com/avast/retry-go"
"github.com/tidwall/gjson"
"io"
"net/http"
"strings"
)
func Translate(text, sourceLang, targetLang string) (string, error) {
if len(sourceLang) == 0 {
lang := whatlanggo.DetectLang(text)
deepLLang := strings.ToUpper(lang.Iso6391())
sourceLang = deepLLang
}
if len(targetLang) == 0 {
targetLang = "EN"
}
if len(text) == 0 {
return "", errors.New("No Translate Text Found")
}
response, err := post("https://api.deeplx.org/translate", RequestParams{
Text: text,
SourceLang: sourceLang,
TargetLang: targetLang,
})
if err != nil {
return "", err
}
if gjson.Get(string(response), "code").Int() != 200 {
return "", errors.New(gjson.Get(string(response), "message").String())
}
return gjson.Get(string(response), "data").String(), nil
}
type RequestParams struct {
Text string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
}
func post(url string, request RequestParams) ([]byte, error) {
jsonBody, _ := json.Marshal(request)
params := strings.NewReader(string(jsonBody))
var body []byte
err := retry.Do(
func() error {
response, err := http.Post(url, "application/json", params)
if err == nil {
defer func() {
_ = response.Body.Close()
}()
body, err = io.ReadAll(response.Body)
}
return err
},
retry.Attempts(3),
retry.LastErrorOnly(true),
)
return body, err
}