Files
mtusi2026lab5/dto/create_message_json.go
T
2026-11-10 20:42:03 +03:00

34 lines
1.1 KiB
Go

package dto
import (
"bytes"
"encoding/json"
"errors"
)
// Keep absent attachment_ids equivalent to [], while rejecting JSON null and
// wrong types rather than quietly treating them as an empty message body.
func (r *CreateMessageRequest) UnmarshalJSON(data []byte) error {
type payload CreateMessageRequest
var fields map[string]json.RawMessage
if err := json.Unmarshal(data, &fields); err != nil || fields == nil {
return errors.New("Ожидается JSON-объект")
}
text, exists := fields["text"]
if !exists || bytes.Equal(bytes.TrimSpace(text), []byte("null")) {
return errors.New("Требуется строка text")
}
if ids, exists := fields["attachment_ids"]; exists && bytes.Equal(bytes.TrimSpace(ids), []byte("null")) {
return errors.New("attachment_ids должен быть массивом")
}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
var decoded payload
if err := decoder.Decode(&decoded); err != nil {
return err
}
decoded.ChatID = r.ChatID
*r = CreateMessageRequest(decoded)
return nil
}