2022-06-12 00:53:39 +00:00
|
|
|
package ipinfo
|
2021-05-08 23:37:32 +00:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2023-05-20 19:58:18 +00:00
|
|
|
"net/netip"
|
2021-05-08 23:37:32 +00:00
|
|
|
)
|
|
|
|
|
|
2022-06-12 00:09:01 +00:00
|
|
|
// FetchMultiInfo obtains the public IP address information for every IP
|
2021-05-08 23:37:32 +00:00
|
|
|
// addresses provided and returns a slice of results with the corresponding
|
|
|
|
|
// order as to the IP addresses slice order.
|
|
|
|
|
// If an error is encountered, all the operations are canceled and
|
|
|
|
|
// an error is returned, so the results returned should be considered
|
|
|
|
|
// incomplete in this case.
|
2023-05-20 19:58:18 +00:00
|
|
|
func (f *Fetch) FetchMultiInfo(ctx context.Context, ips []netip.Addr) (
|
2022-06-12 00:53:39 +00:00
|
|
|
results []Response, err error) {
|
2021-05-08 23:37:32 +00:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
|
|
|
|
|
|
type asyncResult struct {
|
|
|
|
|
index int
|
2022-06-12 00:53:39 +00:00
|
|
|
result Response
|
2021-05-08 23:37:32 +00:00
|
|
|
err error
|
|
|
|
|
}
|
|
|
|
|
resultsCh := make(chan asyncResult)
|
|
|
|
|
|
|
|
|
|
for i, ip := range ips {
|
2023-05-20 19:58:18 +00:00
|
|
|
go func(index int, ip netip.Addr) {
|
2021-05-08 23:37:32 +00:00
|
|
|
aResult := asyncResult{
|
|
|
|
|
index: index,
|
|
|
|
|
}
|
2022-06-12 00:09:01 +00:00
|
|
|
aResult.result, aResult.err = f.FetchInfo(ctx, ip)
|
2021-05-08 23:37:32 +00:00
|
|
|
resultsCh <- aResult
|
|
|
|
|
}(i, ip)
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-12 00:53:39 +00:00
|
|
|
results = make([]Response, len(ips))
|
2021-05-08 23:37:32 +00:00
|
|
|
for i := 0; i < len(ips); i++ {
|
|
|
|
|
aResult := <-resultsCh
|
|
|
|
|
if aResult.err != nil {
|
|
|
|
|
if err == nil {
|
|
|
|
|
// Cancel on the first error encountered
|
|
|
|
|
err = aResult.err
|
|
|
|
|
cancel()
|
|
|
|
|
}
|
|
|
|
|
continue // ignore errors after the first one
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
results[aResult.index] = aResult.result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
close(resultsCh)
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
|
|
return results, err
|
|
|
|
|
}
|