I'm relatively new to Go and trying to find a better way to retrieve information from the REST API at the same time. The goal is to make multiple simultaneous API calls, with each call returning a different data type.
I currently have:
s := NewClient() c1 := make(chan map[string]Service) c2 := make(chan map[string]ServicePlan) c3 := make(chan map[string]ServiceInstance) c4 := make(chan map[string]ServiceBinding) c5 := make(chan map[string]Organization) c6 := make(chan map[string]Space) go func() { c1 <- GetServices(s) }() go func() { c2 <- GetServicePlans(s) }() go func() { c3 <- GetServiceInstances(s) }() go func() { c4 <- GetServiceBindings(s) }() go func() { c5 <- GetOrganizations(s) }() go func() { c6 <- GetSpaces(s) }() services := <- c1 servicePlans := <- c2 serviceInstances := <- c3 serviceBindings := <- c4 orgs := <- c5 spaces := <- c6
but I was wondering if there is a better way to write this.
EDIT: It is still ugly, but reduced the number of channels to one:
c := make(chan interface{}) var ( services map[string]Service servicePlans map[string]ServicePlan serviceInstances map[string]ServiceInstance serviceBindings map[string]ServiceBinding orgs map[string]Organization spaces map[string]Space ) go func() { c <- GetServices(s) }() go func() { c <- GetServicePlans(s) }() go func() { c <- GetServiceInstances(s) }() go func() { c <- GetServiceBindings(s) }() go func() { c <- GetOrganizations(s) }() go func() { c <- GetSpaces(s) }() for i := 0; i < 6; i++ { v := <-c switch v := v.(type) { case map[string]Service: services = v case map[string]ServicePlan: servicePlans = v case map[string]ServiceInstance: serviceInstances = v case map[string]ServiceBinding: serviceBindings = v case map[string]Organization: orgs = v case map[string]Space: spaces = v } }
I would really like the way to do this, so I donβt need to hard code the loop, which needs to be run 6 times. I really tried to make a list of functions to run and do it in such a way as to remove duplicate go func calls, but since all functions have different types of returned data, I got all type mismatch errors and you cannot fake it using func(api) interface{} , as this only creates panic at runtime.
source share