feat: support Official API (#74)

This commit is contained in:
Vincent Young 2023-11-27 12:03:32 -05:00 committed by GitHub
parent cba84471ba
commit 128225979a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

101
main.go
View File

@ -2,7 +2,7 @@
* @Author: Vincent Young * @Author: Vincent Young
* @Date: 2023-07-01 21:45:34 * @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Young * @LastEditors: Vincent Young
* @LastEditTime: 2023-11-18 04:12:49 * @LastEditTime: 2023-11-27 11:59:51
* @FilePath: /DeepLX/main.go * @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* *
@ -17,6 +17,7 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
@ -33,6 +34,7 @@ import (
var port int var port int
var token string var token string
var authKey string
func init() { func init() {
const ( const (
@ -123,8 +125,75 @@ type ResData struct {
TargetLang string `json:"target_lang"` TargetLang string `json:"target_lang"`
} }
type Payload struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
SourceLang string `json:"source_lang"`
GlossaryID string `json:"glossary_id"`
}
type Translation struct {
Text string `json:"text"`
}
type TranslationResponse struct {
Translations []Translation `json:"translations"`
}
func translateByAPI(text string, targetLang string, sourceLang string, authKey string) (string, error) {
url := "https://api-free.deepl.com/v2/translate"
textArray := strings.Split(text, "\n")
payload := Payload{
Text: textArray,
TargetLang: targetLang,
SourceLang: sourceLang,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "DeepL-Auth-Key "+authKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Parsing the response
var translationResponse TranslationResponse
err = json.Unmarshal(body, &translationResponse)
if err != nil {
return "", err
}
// Concatenating the translations
var sb strings.Builder
for _, translation := range translationResponse.Translations {
sb.WriteString(translation.Text)
}
return sb.String(), nil
}
func main() { func main() {
// Parsing the command-line flags // Parsing the command-line flags
flag.StringVar(&authKey, "authkey", "", "The authentication key for DeepL API")
flag.Parse() flag.Parse()
// Displaying initialization information // Displaying initialization information
@ -146,6 +215,18 @@ func main() {
fmt.Println("Access token is set. Use the Authorization: Bearer <token> header to access /translate.") fmt.Println("Access token is set. Use the Authorization: Bearer <token> header to access /translate.")
} }
if authKey == "" {
envAuthKey, ok := os.LookupEnv("AUTHKEY")
if ok {
authKey = envAuthKey
fmt.Println("Authentication key is set from the environment variable.")
} else {
fmt.Println("Authentication key is not set. You can set it using the -authkey flag or the AUTHKEY environment variable.")
}
} else {
fmt.Println("Authentication key is set via command-line.")
}
// Generating a random ID // Generating a random ID
id := getRandomNumber() id := getRandomNumber()
@ -280,9 +361,20 @@ func main() {
} }
if resp.StatusCode == http.StatusTooManyRequests { if resp.StatusCode == http.StatusTooManyRequests {
c.JSON(http.StatusTooManyRequests, gin.H{ translatedText, err := translateByAPI(translateText, sourceLang, targetLang, authKey)
"code": http.StatusTooManyRequests, if err != nil {
"message": "Too Many Requests", c.JSON(http.StatusTooManyRequests, gin.H{
"code": http.StatusTooManyRequests,
"message": "Too Many Requests",
})
}
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"id": 1000000,
"data": translatedText,
"source_lang": sourceLang,
"target_lang": targetLang,
"method": "Official API",
}) })
} else { } else {
var alternatives []string var alternatives []string
@ -297,6 +389,7 @@ func main() {
"alternatives": alternatives, "alternatives": alternatives,
"source_lang": sourceLang, "source_lang": sourceLang,
"target_lang": targetLang, "target_lang": targetLang,
"method": "Free",
}) })
} }
}) })