I have the following API which takes an array of ranges of IP addresses and performs concurrent API calls on all of them. Here is the code:
func handler(w http.ResponseWriter, r *http.Request) {
var ipRanges ScanApiBody
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&ipRanges); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
w.WriteHeader(http.StatusBadRequest)
return
}
if len(ipRanges.Ranges) == 0 {
http.Error(w, "No Ranges Provided", http.StatusBadRequest)
w.WriteHeader(http.StatusBadRequest)
return
}
client := &http.Client{
Transport: &digest.Transport{
Username: "root",
Password: "root",
},
}
success := 0
wg := sync.WaitGroup{}
for ri := 0; ri < len(ipRanges.Ranges); ri++ {
ipRange := ipRanges.Ranges[ri]
for ip := ipRange.Start; !ip.Equal(ipRange.End); ip = incrementIP(ip) {
wg.Add(1)
go func(client *http.Client, ip net.IP) {
defer wg.Done()
_, err := checkIpForDevice(client, ip)
if err != nil {
log.Println(err)
} else {
success++
}
}(client, ip)
}
}
wg.Wait()
w.Write([]byte(fmt.Sprintf("Successfull: %v", success)))
}
I am sure there is some basic mistake since my knowledge of concurrency in Go is barely 1-2 days old. I am noticing that if I add more and more ranges of IP addresses, the API takes longer and longer. I expect it to be basically the same across the board since all API calls are being made at the same time.
What might I be doing wrong? Is my approach incorrect?