Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to publish and consume make(map[string]string) in rabbitmq go lang

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:        ????,
        })
like image 710
Naresh Avatar asked Oct 28 '25 11:10

Naresh


2 Answers

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.

like image 137
Ismayil Niftaliyev Avatar answered Oct 31 '25 09:10

Ismayil Niftaliyev


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?

like image 27
Jean-Sébastien Pédron Avatar answered Oct 31 '25 09:10

Jean-Sébastien Pédron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!