Hi folks. I have an ID uint
on a model. I need to add to a RabbitMQ stack which only takes a slice of bytes, and I want to pass this ID as a slice of bytes. On my next service I want to grab this slice of bytes, convert it to a string (or back to uint would even be OK), and do a lookup based on it. I am fairly new to typed languages, and this is my first real roadblock so far.
I tried this:
func UIntToByteSlice(num uint) []byte {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, uint64(num))
return b
}
but when I pull the string(ID)
on my other service, ID
being the slice of bytes, I just get a unicode box with "0 0 0 2" in it. I am definitely pulling the byte slice off the stacks, I just can't get the hang of conversion, and tbh, this is my first real foray into "LittleEndian" and stuff like this. Can anyone assist or point me in the right direction please? : )
评论:
RenThraysk:
diabetesjones:The receiving end has to read the value using binary.LittleEndian.Uint64()
epiris:Thank you very much!! This works, but I started reading more about conversion, and it seems simpler to do this if I want the end result as a string (which would be better)
// UIntToByteSlice is a helper function to convert down to byte slices to add to the // RabbitMQ stack func UIntToByteSlice(num uint) []byte { str := strconv.Itoa(int(num)) return []byte(str) }
And now on my receiving end I just grab the ID and do
string(ID)
.
diabetesjones:I would put the message in a struct and use json, or use the binary package if performance is a concern. Well formed standard encoding scheme is “simpler” in my opinion.
gergo254:That does sound better as it enforces a standard on both ends. Will do that monday!
Or he can even try protobuf. :)
