fix(service): treat a null text as no text, and read that from the field

UnmarshalJSON sent `null` down the string branch, where json.Unmarshal into a
string is a documented no-op, so `{"text":null}` decoded to `[""]` and was
indistinguishable from `{"text":""}` for the rest of the request. On main both
were an error, but this branch answers an empty text with itself, so null
quietly became a 200 instead.

A JSON null is a present key with no value, so it leaves the zero value now —
the same Texts == nil a body with no `text` key has — and the handler refuses
both with 400 Invalid request payload, testing the field directly instead of
re-deriving the decoder with `!Batch && len(Texts) == 0`. Every shape that
names text, including `"text": []`, still decodes to a non-nil Texts and is
answered rather than refused.

Refs #244.
This commit is contained in:
JounQin
2026-10-11 00:40:57 +08:00
parent b28dcd4958
commit ee1114252e
3 changed files with 12 additions and 7 deletions
+9 -4
View File
@@ -91,8 +91,7 @@ type PayloadTranslate struct {
// 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.
// 400 Invalid request payload; null names no text, like a body without the key.
type PayloadText struct {
Texts []string
Batch bool
@@ -100,7 +99,8 @@ type PayloadText struct {
// UnmarshalJSON implements json.Unmarshaler.
func (p *PayloadText) UnmarshalJSON(data []byte) error {
if trimmed := bytes.TrimSpace(data); len(trimmed) > 0 && trimmed[0] == '[' {
trimmed := bytes.TrimSpace(data)
if len(trimmed) > 0 && trimmed[0] == '[' {
var texts []string
if err := json.Unmarshal(trimmed, &texts); err != nil {
return err
@@ -109,6 +109,11 @@ func (p *PayloadText) UnmarshalJSON(data []byte) error {
return nil
}
// A JSON null names no text: leave the zero value, so Texts stays nil.
if string(trimmed) == "null" {
return nil
}
var text string
if err := json.Unmarshal(data, &text); err != nil {
return err
@@ -162,7 +167,7 @@ func Router(cfg *Config) *gin.Engine {
// A body without `text` never named a text to translate, which is a
// payload error. `"text": []` names a list that happens to be empty,
// and is answered with an empty list, so it is not caught here.
if !req.Text.Batch && len(req.Text.Texts) == 0 {
if req.Text.Texts == nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid request payload",