lab4 done
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user