I am experiencing some integer overflow error. I have a micro service application built using golang and go-micro as micro service framework. And I am using NATS as message broker.
my micro service payloads are in the format
map[string]interface{}
The problem occurs when I publish a payload which contains a uint64 such as
var id uint64 = 512281913614499841
message := map[string]inteface{}
message["id"] = id
(this is a unique ID generated by cockroachdb), when a subscriber receives this message as byte and unmarshals this to a uint64, i realize that a overflow occurs and the value becomes
512281913614499840 //this should be 512281913614499841
notice the 0 at the end instead of 1
I have created 2 functions (overFlowError and noOverflow) - see below.
the function overFlowError simulates code that causes overflow
and noOverflow prints the correct result because i use payload in this format map[string][struct] instead of map[string]interface
type UserType struct {
Email string `json:"email"`
ID int64 `json:"id"`
}
func overFlowError() {
var id int64 = 512281913614499841
user := UserType{
Email: "example",
ID: id,
}
message := map[string]interface{}{
"data": user,
}
//mashal to byte to simulate service payload
servicePayload, err := json.Marshal(message)
if err != nil {
log.Println(err)
}
var receivedMessage map[string]interface{}
json.Unmarshal(servicePayload, &receivedMessage)
var myUser UserType
mapstructure.Decode(receivedMessage["data"], &myUser)
log.Println("---receivedMessage:", myUser.ID) //prints 512281913614499840 - incorrect
}
No over flow
type UserType struct {
Email string `json:"email"`
ID int64 `json:"id"`
}
func noOverflow() {
var id int64 = 512281913614499841
message := map[string]UserType{}
message["data"] = UserType{
Email: "example",
ID: id,
}
byteMessage, err := json.Marshal(message)
if err != nil {
log.Println(err)
}
var msgMap map[string]UserType
json.Unmarshal(byteMessage, &msgMap)
log.Println("---myUser:", msgMap["data"].ID) // prints 512281913614499841 - correct
}
to over avoid a lot of code rewrite, I am left with the first option which i have simulated in the overFlowError function and also explained above
is there a fix to this problem?