I am learning golang and want to write generic response from microservices response.
My General Response is like:
type GeneralResponse struct {
Success string
Message string
Data string
Error string
}
In the Data
section I want to return any json, say list of Person
, Instruments
or any type of objects.
But it should be another json. I tried assigning other json objects but it did not work. It is fine if I dump json array as string into it but it should unmarshal from receiver end. How should I go about it?
I am trying over here. https://play.golang.org/p/dc0uKtS76aA
You should use RawMessage in the type definition
type GeneralResponse struct {
Success string
Message string
Data json.RawMessage
Error string
}
and subsequently push a Marshal
led json into that attribute. You can do that by encoding other types in []byte
s and setting them to the Data
attribute.
If you put marshalled JSON into a string, it will be marshalled as a string (because it's a string) and the receiving end will have to unmarshal it twice (because it's been marshalled twice). What you want is probably more along the lines of:
type GeneralResponse struct {
Success string
Message string
Data interface{} // interface{} can be anything
Error string
}
This way you can put any data into Data
and it will be marshalled directly into the response.
json.RawMessage comes to rescue in case you wants to capture whole json without knowing its format.
type GeneralResponse struct {
Success string
Message string
Data json.RawMessage
Error string
}
Checkout this code. I have modified your code to dump data into response
You can use json.RawMessage
for that. I have implemented the encoding part, you find more here to decode - https://golang.org/pkg/encoding/json/#RawMessage