feat: add support for proxy

rename proxy name

rename proxy name
This commit is contained in:
furacas 2023-09-02 11:58:11 +08:00
parent eb6afa8106
commit dbb3d6e7e7
2 changed files with 28 additions and 3 deletions

View File

@ -60,6 +60,11 @@
# or # or
./deeplx -port 3333 ./deeplx -port 3333
``` ```
### Proxy
If you need to set up a proxy, you can set the environment variable `DEEPLX_PROXY`, for example `DEEPLX_PROXY=http://127.0.0.1:7890`
or `DEEPLX_PROXY=socks5://127.0.0.1:7890`. If the variable is empty, it will not be enabled.
If the proxy requires username and password for authentication, then use `http://username:password@ip:port` or `socks5://username:password@ip:port`.
### Run with Docker ### Run with Docker
```bash ```bash

26
main.go
View File

@ -20,6 +20,7 @@ import (
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
"net/url"
"os" "os"
"strings" "strings"
"time" "time"
@ -165,7 +166,7 @@ func main() {
"message": "No Translate Text Found", "message": "No Translate Text Found",
}) })
} else { } else {
url := "https://www2.deepl.com/jsonrpc" requestURL := "https://www2.deepl.com/jsonrpc"
id = id + 1 id = id + 1
postData := initData(sourceLang, targetLang) postData := initData(sourceLang, targetLang)
text := Text{ text := Text{
@ -190,7 +191,7 @@ func main() {
post_byte = []byte(postStr) post_byte = []byte(postStr)
reader := bytes.NewReader(post_byte) reader := bytes.NewReader(post_byte)
request, err := http.NewRequest("POST", url, reader) request, err := http.NewRequest("POST", requestURL, reader)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
@ -209,7 +210,26 @@ func main() {
request.Header.Set("x-app-version", "2.9.1") request.Header.Set("x-app-version", "2.9.1")
request.Header.Set("Connection", "keep-alive") request.Header.Set("Connection", "keep-alive")
client := &http.Client{} proxyAddr := os.Getenv("DEEPLX_PROXY")
var client *http.Client
if proxyAddr != "" {
proxyURL, err := url.Parse(proxyAddr)
if err != nil {
log.Println(fmt.Errorf("error parsing proxy address: %s", proxyAddr))
return
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
client = &http.Client{
Transport: transport,
}
} else {
client = &http.Client{}
}
resp, err := client.Do(request) resp, err := client.Do(request)
if err != nil { if err != nil {
log.Println(err) log.Println(err)