Senior
Como escrever solicitações HTTP paralelas em Golang?
sobes.tech IA
Resposta da IA
Em Go, para realizar pedidos HTTP em paralelo, normalmente usa-se goroutines e canais para recolher os resultados. Exemplo:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func fetch(url string, ch chan<- string) {
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprintf("error: %v", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
ch <- fmt.Sprintf("error reading body: %v", err)
return
}
ch <- string(body)
}
func main() {
urls := []string{
"https://example.com",
"https://golang.org",
"https://httpbin.org/get",
}
ch := make(chan string)
for _, url := range urls {
go fetch(url, ch)
}
for range urls {
fmt.Println(<-ch)
}
}
Aqui, para cada URL, inicia-se uma goroutine que faz a requisição HTTP e envia o resultado para o canal. A função principal lê do canal tantas vezes quanto o número de pedidos, assim recolhendo todas as respostas em paralelo.