-
Notifications
You must be signed in to change notification settings - Fork 5
/
fy.go
95 lines (80 loc) · 1.78 KB
/
fy.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package fy
import (
"context"
"sync"
"time"
)
const (
Chinese = "zh-CN"
English = "en"
Russian = "ru"
Japanese = "ja"
German = "de"
French = "fr"
Korean = "ko"
Spanish = "es"
UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
)
var Translators = []translator{
baidu, bing, google, sogou, tencent, youdao, deepl, caiyun,
}
// Request translation request
type Request struct {
// FromLang the from language of the translation
FromLang string
// ToLang the to language of the translation
ToLang string
// Text translation text
Text string
}
// Response translation response
type Response struct {
// Name the translator name
Name string
// Homepage the translator homepage
Homepage string
// Result the translation result
Result string
// Err the translation error
Err error
}
func newResp(t translator) *Response {
name, homepage := t.Desc()
return &Response{
Name: name,
Homepage: homepage,
}
}
type translator interface {
Desc() (name string, source string)
translate(context.Context, Request) *Response
}
func AsyncTranslate(eachTranslatorTimeout time.Duration, req *Request, ts ...string) <-chan *Response {
var limitMap map[string]bool
if len(ts) > 0 {
limitMap = map[string]bool{}
for _, name := range ts {
limitMap[name] = true
}
}
wg := sync.WaitGroup{}
ch := make(chan *Response)
for _, t := range Translators {
name, _ := t.Desc()
if limitMap != nil && !limitMap[name] {
continue
}
wg.Add(1)
go func(t translator) {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), eachTranslatorTimeout)
defer cancel()
ch <- t.translate(ctx, *req)
}(t)
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}