This repository has been archived by the owner on Sep 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate_array.go
70 lines (55 loc) · 1.54 KB
/
translate_array.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
package mstranslator
import (
"bytes"
"encoding/xml"
"net/http"
"strings"
)
const (
translate_array_url = "http://api.microsofttranslator.com/V2/Http.svc/TranslateArray"
)
type TranslateArrayResponse struct {
From string `xml:"From"`
Text string `xml:"TranslatedText"`
}
type TranslateArrayResponseBody struct {
XMLName xml.Name `xml:"ArrayOfTranslateArrayResponse"`
TranslateArrayResponses []TranslateArrayResponse `xml:"TranslateArrayResponse"`
}
func TranslateArray(words []string, token string) ([]string, error) {
client := &http.Client{}
results := make([]string, 10)
texts := make([]string, 10)
for _, w := range words {
str := `<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">` + w + "</string>"
texts = append(texts, str)
}
xml_body := []byte(`
<TranslateArrayRequest>
<AppId />
<From>en</From>
<Texts>` + strings.Join(texts, "") + `</Texts>
<To>ja</To>
</TranslateArrayRequest>
`)
req, err := http.NewRequest("POST", translate_array_url, bytes.NewBuffer(xml_body))
if err != nil {
return results, err
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Content-Type", "text/xml")
resp, err := client.Do(req)
if err != nil {
return results, err
}
defer resp.Body.Close()
data := &TranslateArrayResponseBody{}
decoder := xml.NewDecoder(resp.Body)
if err := decoder.Decode(data); err != nil {
return results, err
}
for _, v := range data.TranslateArrayResponses {
results = append(results, v.Text)
}
return results, nil
}