-
Notifications
You must be signed in to change notification settings - Fork 2
/
translate.go
58 lines (54 loc) · 1.27 KB
/
translate.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
package google
import (
"bytes"
"errors"
"io/ioutil"
"net/url"
"regexp"
"strings"
)
var (
reTranslations = regexp.MustCompile("^\\[{2}(.*?)\\]{2},")
reTranslation = regexp.MustCompile("\\[\"([^\"]+)\"")
)
type Translation struct {
Text string
}
func (s *Session) Translate(text, sourcelang, targetlang string) (Translation, error) {
var t Translation
r, err := s.request("POST",
"https://translate.googleapis.com/translate_a/single",
bytes.NewBufferString(url.Values{
"client": []string{"gtx"},
"ie": []string{"UTF-8"},
"oe": []string{"UTF-8"},
"sl": []string{sourcelang},
"tl": []string{targetlang},
"dt": []string{"t"},
"q": []string{text},
}.Encode()))
if err != nil {
return t, err
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
r.Body.Close()
return t, err
}
r.Body.Close()
trs := reTranslations.FindSubmatch(data)
if trs == nil {
return t, errors.New("server returned unexpected result")
}
strs := strings.Replace(string(trs[1]), "\\n", "\n", -1)
tr := reTranslation.FindAllStringSubmatch(strs, -1)
if tr == nil {
return t, errors.New("server returned unexpected result")
}
b := bytes.NewBufferString("")
for _, t := range tr {
b.WriteString(t[1])
}
t.Text = b.String()
return t, nil
}