-
Notifications
You must be signed in to change notification settings - Fork 0
/
lingvanex.go
108 lines (92 loc) · 2.39 KB
/
lingvanex.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
96
97
98
99
100
101
102
103
104
105
106
107
108
package lingvanex
import (
"context"
"fmt"
"net"
"net/http"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/powerman/structlog"
)
const (
defaultRetryMax = 5
defaultConnTimeout = 15 * time.Second
defaultURL = "https://api-b2b.backenster.com/b1/api/v3"
)
type Client interface {
SetRetryMax(retryMax int) Client
SetConnTimeout(connTimeout time.Duration) Client
SetURL(apiURL string) Client
SetKey(apiKey string) Client
SetEnableTransliteration(enable bool) Client
GetLanguages(ctx context.Context, code string) ([]Language, error)
Translate(ctx context.Context, q, source, target string) (*TranslateResponse, error)
}
type client struct {
transliteration bool
retryMax int
apiURL string
apiKey string
languagesURL string
translateURL string
connTimeout time.Duration
httpClient *retryablehttp.Client
logger *structlog.Logger
}
func NewTranslator() Client {
c := &client{
retryMax: defaultRetryMax,
connTimeout: defaultConnTimeout,
logger: structlog.New(),
}
c.initClient()
return c
}
func (c *client) SetRetryMax(retryMax int) Client {
c.retryMax = retryMax
return c
}
func (c *client) SetConnTimeout(connTimeout time.Duration) Client {
c.connTimeout = connTimeout
return c
}
func (c *client) SetURL(apiURL string) Client {
c.apiURL = apiURL
c.translateURL = fmt.Sprintf("%s/translate", c.apiURL)
c.languagesURL = fmt.Sprintf("%s/getLanguages", c.apiURL)
return c
}
func (c *client) SetKey(apiKey string) Client {
c.apiKey = apiKey
return c
}
func (c *client) SetEnableTransliteration(enable bool) Client {
c.transliteration = enable
return c
}
func (c *client) initClient() {
client := &http.Client{
Timeout: c.connTimeout,
Transport: &http.Transport{
DialContext: (&net.Dialer{}).DialContext,
MaxIdleConns: 10,
MaxIdleConnsPerHost: 10,
},
}
httpClient := &retryablehttp.Client{
RetryMax: c.retryMax,
Logger: c.logger,
HTTPClient: client,
Backoff: retryablehttp.LinearJitterBackoff,
CheckRetry: retryablehttp.DefaultRetryPolicy,
RequestLogHook: func(logger retryablehttp.Logger, request *http.Request, i int) {
if i > 0 {
logger.Printf("retry url %s attempt %d", request.URL.Path, i)
}
},
}
c.httpClient = httpClient
c.apiURL = defaultURL
c.translateURL = fmt.Sprintf("%s/translate", c.apiURL)
c.languagesURL = fmt.Sprintf("%s/getLanguages", c.apiURL)
}