diff --git a/chat/message.go b/chat/message.go index 0d11f01..f80c05b 100644 --- a/chat/message.go +++ b/chat/message.go @@ -43,7 +43,7 @@ const ( // Message is a message sent by other type Message struct { - Text string `json:"text,omitempty"` + Text string `json:"text"` Bold bool `json:"bold,omitempty"` //粗体 Italic bool `json:"italic,omitempty"` //斜体 @@ -67,8 +67,38 @@ type Message struct { Extra []Message `json:"extra,omitempty"` } +// Same as Message, but "Text" is omitempty +type translateMsg struct { + Text string `json:"text,omitempty"` + + Bold bool `json:"bold,omitempty"` + Italic bool `json:"italic,omitempty"` + UnderLined bool `json:"underlined,omitempty"` + StrikeThrough bool `json:"strikethrough,omitempty"` + Obfuscated bool `json:"obfuscated,omitempty"` + + Font string `json:"font,omitempty"` + Color string `json:"color,omitempty"` + + Insertion string `json:"insertion,omitempty"` + ClickEvent *ClickEvent `json:"clickEvent,omitempty"` + HoverEvent *HoverEvent `json:"hoverEvent,omitempty"` + + Translate string `json:"translate"` + With []json.RawMessage `json:"with,omitempty"` + Extra []Message `json:"extra,omitempty"` +} + type jsonMsg Message +func (m Message) MarshalJSON() ([]byte, error) { + if m.Translate != "" { + return json.Marshal(translateMsg(m)) + } else { + return json.Marshal(jsonMsg(m)) + } +} + //UnmarshalJSON decode json to Message func (m *Message) UnmarshalJSON(raw []byte) (err error) { if len(raw) == 0 { diff --git a/chat/message_test.go b/chat/message_test.go index fd79739..face916 100644 --- a/chat/message_test.go +++ b/chat/message_test.go @@ -2,7 +2,9 @@ package chat_test import ( "bytes" + "encoding/json" "fmt" + "strings" "testing" "github.com/Tnze/go-mc/chat" @@ -134,6 +136,31 @@ func TestMessage_Append_issue148(t *testing.T) { } } +func TestMessage_MarshalJSON_issue151(t *testing.T) { + // The "text" field should be omitted when "translate" exist. + // And NOT omitted when "extra" so. + // That is, we should correctly generate these chat messages: + // {"text":"","extra":["str1", "str2"]} and + // {"translate":"translation.test.escape","with":["str1","str2"]} + mustJson := func(msg *chat.Message) string { + data, err := json.Marshal(msg) + if err != nil { + t.Fatal(err) + } + return string(data) + } + // "" + "Hello, world!" + msg1 := chat.Text("").Append(chat.TranslateMsg("translation.test.none")) + if msg := mustJson(&msg1); !strings.Contains(msg, "text") { + t.Fatalf("%s doesn't contain %s", msg, "text") + } + // + msg2 := chat.TranslateMsg("translation.test.none") + if msg := mustJson(&msg2); strings.Contains(msg, "text") { + t.Fatalf("%s contains %s", msg, "text") + } +} + func ExampleTranslateMsg() { fmt.Println(chat.TranslateMsg("translation.test.none")) fmt.Println(chat.TranslateMsg(