Skip to content

Commit

Permalink
Merge pull request #345 from ctron/feature/accept_buffer_1
Browse files Browse the repository at this point in the history
Allow using bytes.Buffer as payload
  • Loading branch information
Al S-M committed Aug 29, 2019
2 parents f718010 + de4d1fa commit 08f8223
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
9 changes: 6 additions & 3 deletions client.go
Expand Up @@ -18,6 +18,7 @@
package mqtt

import (
"bytes"
"errors"
"fmt"
"net"
Expand Down Expand Up @@ -578,11 +579,13 @@ func (c *client) Publish(topic string, qos byte, retained bool, payload interfac
pub.Qos = qos
pub.TopicName = topic
pub.Retain = retained
switch payload.(type) {
switch p := payload.(type) {
case string:
pub.Payload = []byte(payload.(string))
pub.Payload = []byte(p)
case []byte:
pub.Payload = payload.([]byte)
pub.Payload = p
case bytes.Buffer:
pub.Payload = p.Bytes()
default:
token.setError(fmt.Errorf("Unknown payload type"))
return token
Expand Down
18 changes: 18 additions & 0 deletions fvt_client_test.go
Expand Up @@ -142,6 +142,24 @@ func Test_Publish_3(t *testing.T) {
c.Disconnect(250)
}

func Test_Publish_BytesBuffer(t *testing.T) {
ops := NewClientOptions()
ops.AddBroker(FVTTCP)
ops.SetClientID("Publish_BytesBuffer")

c := NewClient(ops)
token := c.Connect()
if token.Wait() && token.Error() != nil {
t.Fatalf("Error on Client.Connect(): %v", token.Error())
}

payload := bytes.NewBufferString("Publish qos0")

c.Publish("test/Publish", 0, false, payload)

c.Disconnect(250)
}

func Test_Subscribe(t *testing.T) {
pops := NewClientOptions()
pops.AddBroker(FVTTCP)
Expand Down

0 comments on commit 08f8223

Please sign in to comment.