I have a situation where I need to interact with a bunch of API's that all have similar purposes but different data structures returned. I need to operate the same way on data from all the API's but I then also need to maybe send that data back to the API at a later time so it can perform further operations on it.
type API1Response struct {
Time time.Time
Price int64
Status int
ID string
}
type API2Response struct {
Price float64
Status string
ID int64
}
// and more API responsed that have irreconcilable differences in their structures
both APIs have similar methods, like Buy
and Sell
and CancelOrder
so I thought I could use interfaces to make my calls to the methods more usable but then I will have to make the methods return interface{}
instead of returning their specific API response...
now imagine the situation where I want to Buy
and I get API1Response
. So I call the method defined in my interface but then I want to CancelOrder
which needs me to send API1Response
back to the API. How can I convert the interface back to API1Response properly?
the only way I could think to do it would be to make a long switch case that tries to convert to every possible data type but IDK if that is idiomatic or error prone in the long run...
if t, ok := emptyInterface.(API1Response); ok {
//do stuff
} else if t, ok := emptyInterface.(API2Response); ok {
// do stuff
}
How would you go about solving this problem idiomatically in go?