2

I have multiple objects of key-value type which i need to send to RabbitMQ and hence forward would consume them. So, after going through this RabbitMQ link. It only tells the way to publish a simple plain text message. Can anyone tell me how to publish and consume map objects in RabbitMQ go lang?

     m := make(map[string]string)
     m["col1"] = "004999010640000"
     m["col2"] = "awadwaw"
     m["col3"] = "13"  

     err = ch.Publish(
        "EventCaptureData-Exchange", // exchange
        q.Name + "Key",          // routing key
        true,           // mandatory                            
        false,           // immediate
        amqp.Publishing{
            ContentType: "?????",
            Body:        ????,
        })
Naresh
  • 5,073
  • 12
  • 67
  • 124

2 Answers2

6

It's so simple. You can use json and bytes packages to serialize and deserialize messages. Prepared this example for you:

type Message map[string]interface{}

func serialize(msg Message) ([]byte, error) {
    var b bytes.Buffer
    encoder := json.NewEncoder(&b)
    err := encoder.Encode(msg)
    return b.Bytes(), err
}

func deserialize(b []byte) (Message, error) {
    var msg Message
    buf := bytes.NewBuffer(b)
    decoder := json.NewDecoder(buf)
    err := decoder.Decode(&msg)
    return msg, err
}

Yeah, basically that's it. Body field in RabbitMQ library is byte array, therefore all you need are just converting to/from your data structure to/from byte array.

3

You need to serialize your Go object to eg. base64 text before publishing it. In your consumer, you then deserialize it to get back your initial object. See "Golang serialize and deserialize back" for an example in Go.

For the content type, I'm not sure what is the most appropriate. application/octet-stream?

Community
  • 1
  • 1
  • 1
    since the type is mostly string data (`map[string]string`), json is going to be more compact than a gob in base64. – JimB Mar 23 '16 at 14:44
  • I agree, JSON is probably a better choice for many reasons (easier debugging, possibility to read and interpret it from another language, etc.). I just mentionned base64 here because I found an example quickly. I'm not a Go developer so I couldn't prepare a JSON-based example. – Jean-Sébastien Pédron Mar 23 '16 at 15:25