Skip to content

Commit

Permalink
fix: MessageID String() repr
Browse files Browse the repository at this point in the history
  • Loading branch information
fumiama committed May 4, 2024
1 parent 7941fa5 commit c9c0e1f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
14 changes: 14 additions & 0 deletions message/message.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package message

import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/hex"
Expand Down Expand Up @@ -325,6 +326,19 @@ func NewMessageIDFromInteger(raw int64) (m MessageID) {
return
}

func (m MessageID) MarshalJSON() ([]byte, error) {
sb := bytes.NewBuffer(make([]byte, 0, len(m.s)+2))
_, err := strconv.ParseInt(m.s, 10, 64)
if err != nil {
sb.WriteByte('"')
json.HTMLEscape(sb, []byte(m.s))
sb.WriteByte('"')
} else {
sb.WriteString(m.s)
}
return sb.Bytes(), nil
}

func (m MessageID) String() string {
return m.s
}
Expand Down
43 changes: 43 additions & 0 deletions message/message_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package message

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"
)

func TestMessageID(t *testing.T) {
id := NewMessageIDFromString("test case")
msg := Message([]MessageSegment{Reply(id)})
data, err := json.Marshal(&msg)
if err != nil {
t.Fatal(err)
}
t.Log(string(data))
if !assert.Equal(t, `[{"type":"reply","data":{"id":"test case"}}]`, string(data)) {
t.Fail()
}
id = NewMessageIDFromInteger(-1008611)
paras := map[string]interface{}{}
paras["message_id"] = id
data, err = json.Marshal(&paras)
if err != nil {
t.Fatal(err)
}
t.Log(string(data))
if !assert.Equal(t, `{"message_id":-1008611}`, string(data)) {
t.Fail()
}
id = NewMessageIDFromString("test case")
paras = map[string]interface{}{}
paras["message_id"] = id
data, err = json.Marshal(&paras)
if err != nil {
t.Fatal(err)
}
t.Log(string(data))
if !assert.Equal(t, `{"message_id":"test case"}`, string(data)) {
t.Fail()
}
}

0 comments on commit c9c0e1f

Please sign in to comment.