feat(translate): accept an array of texts in POST /translate

`text` now accepts either a single string or an array of strings. A string
is answered with a string in `data` exactly as before; an array is answered
with a position-aligned array, and the whole batch travels in a single
oneshot request, so a caller with many segments needs one round trip
instead of one per segment.

A batch is all-or-nothing: an empty array or an empty element answers with
the existing 404 "No text to translate", and if upstream returns a
different number of translations or leaves one empty the request fails with
503 "Translation failed" instead of returning placeholders or a misaligned
array. The anonymous length cap applies to the total length of the array,
which the README now documents.

Refs #240
This commit is contained in:
JounQin
2026-10-10 11:01:39 +00:00
parent 54158cddd5
commit 97001438d1
6 changed files with 297 additions and 32 deletions
+60 -10
View File
@@ -13,6 +13,8 @@
package service
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
@@ -74,6 +76,47 @@ type PayloadAPI struct {
TagHandling string `json:"tag_handling"`
}
// PayloadTranslate is the request body of POST /translate. Unlike PayloadFree
// (shared with the Pro endpoint), `text` accepts either a single string or an
// array of strings.
type PayloadTranslate struct {
Text PayloadText `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
TagHandling string `json:"tag_handling"`
}
// PayloadText is the `text` field of POST /translate, in either documented
// shape: a bare JSON string or an array of strings. Both are normalized to
// Texts, and Batch records which shape the caller used so the response can
// mirror it. Any other shape (a number, an object, an array holding
// non-strings) fails the payload decode, which the handler reports as
// 400 Invalid request payload; null decodes to the empty string exactly as it
// did when text was a plain string.
type PayloadText struct {
Texts []string
Batch bool
}
// UnmarshalJSON implements json.Unmarshaler.
func (p *PayloadText) UnmarshalJSON(data []byte) error {
if trimmed := bytes.TrimSpace(data); len(trimmed) > 0 && trimmed[0] == '[' {
var texts []string
if err := json.Unmarshal(trimmed, &texts); err != nil {
return err
}
p.Texts, p.Batch = texts, true
return nil
}
var text string
if err := json.Unmarshal(data, &text); err != nil {
return err
}
p.Texts, p.Batch = []string{text}, false
return nil
}
func Router(cfg *Config) *gin.Engine {
// Set Proxy
proxyURL := os.Getenv("PROXY")
@@ -107,7 +150,7 @@ func Router(cfg *Config) *gin.Engine {
// Free API endpoint, No Pro Account required
r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
req := PayloadTranslate{}
if err := c.BindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
@@ -118,7 +161,7 @@ func Router(cfg *Config) *gin.Engine {
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
texts := req.Text.Texts
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
@@ -131,7 +174,7 @@ func Router(cfg *Config) *gin.Engine {
return
}
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "")
result, err := translate.TranslateByDLX(sourceLang, targetLang, texts, tagHandling, proxyURL, "")
if err != nil {
log.Printf("Translation failed: %s", err)
c.JSON(http.StatusInternalServerError, gin.H{
@@ -142,15 +185,22 @@ func Router(cfg *Config) *gin.Engine {
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{
response := gin.H{
"code": http.StatusOK,
"id": result.ID,
"data": result.Data,
"alternatives": result.Alternatives,
"source_lang": result.SourceLang,
"target_lang": result.TargetLang,
"method": result.Method,
})
}
// Mirror the request: a string in `text` answers with a string
// in `data`, an array answers with a position-aligned array.
if req.Text.Batch {
response["data"] = result.Data
} else {
response["data"] = result.Data[0]
}
c.JSON(http.StatusOK, response)
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
@@ -206,7 +256,7 @@ func Router(cfg *Config) *gin.Engine {
return
}
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, dlSession)
result, err := translate.TranslateByDLX(sourceLang, targetLang, []string{translateText}, tagHandling, proxyURL, dlSession)
if err != nil {
log.Printf("Translation failed: %s", err)
c.JSON(http.StatusInternalServerError, gin.H{
@@ -220,7 +270,7 @@ func Router(cfg *Config) *gin.Engine {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"id": result.ID,
"data": result.Data,
"data": result.Data[0],
"alternatives": result.Alternatives,
"source_lang": result.SourceLang,
"target_lang": result.TargetLang,
@@ -267,7 +317,7 @@ func Router(cfg *Config) *gin.Engine {
targetLang = jsonData.TargetLang
}
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, "", proxyURL, "")
result, err := translate.TranslateByDLX(sourceLang, targetLang, []string{translateText}, "", proxyURL, "")
if err != nil {
log.Printf("Translation failed: %s", err)
c.JSON(http.StatusInternalServerError, gin.H{
@@ -282,7 +332,7 @@ func Router(cfg *Config) *gin.Engine {
"translations": []map[string]interface{}{
{
"detected_source_language": result.SourceLang,
"text": result.Data,
"text": result.Data[0],
},
},
})
+48
View File
@@ -0,0 +1,48 @@
package service
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
// The `text` field of POST /translate accepts either shape; decoding uses the
// same encoding/json decoder gin binds request bodies with.
func TestPayloadTextUnmarshalJSON(t *testing.T) {
tests := []struct {
name string
payload string
wantTexts []string
wantBatch bool
wantErr bool
}{
{name: "string", payload: `{"text":"Hello"}`, wantTexts: []string{"Hello"}},
{name: "empty string", payload: `{"text":""}`, wantTexts: []string{""}},
{name: "array", payload: `{"text":["Hello","Good morning"]}`, wantTexts: []string{"Hello", "Good morning"}, wantBatch: true},
{name: "single-element array", payload: `{"text":["Hello"]}`, wantTexts: []string{"Hello"}, wantBatch: true},
{name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true},
{name: "null", payload: `{"text":null}`, wantTexts: []string{""}},
{name: "number", payload: `{"text":1}`, wantErr: true},
{name: "object", payload: `{"text":{}}`, wantErr: true},
{name: "mixed array", payload: `{"text":["Hello",1]}`, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var req PayloadTranslate
err := json.NewDecoder(strings.NewReader(tt.payload)).Decode(&req)
if (err != nil) != tt.wantErr {
t.Fatalf("Decode(%s) error = %v, wantErr %v", tt.payload, err, tt.wantErr)
}
if tt.wantErr {
return
}
if req.Text.Batch != tt.wantBatch {
t.Errorf("Batch = %v, want %v", req.Text.Batch, tt.wantBatch)
}
if !reflect.DeepEqual(req.Text.Texts, tt.wantTexts) {
t.Errorf("Texts = %q, want %q", req.Text.Texts, tt.wantTexts)
}
})
}
}