Skip to content

Instantly share code, notes, and snippets.

@EvilFreelancer
Created May 13, 2023 12:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvilFreelancer/025601bf5f37da46d0653784e4434bd4 to your computer and use it in GitHub Desktop.
Save EvilFreelancer/025601bf5f37da46d0653784e4434bd4 to your computer and use it in GitHub Desktop.
Асинхронная загрузка ссылок (кравлер) Go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
)
func main() {
urls := []string{
"https://api.example.com/users/1",
"https://api.example.com/users/2",
"https://api.example.com/users/3",
"https://api.example.com/users/4",
"https://api.example.com/users/5",
}
var wg sync.WaitGroup
for _, url := range urls {
// Увеличиваем счетчик WaitGroup
wg.Add(1)
go func(url string) {
// Уменьшаем счетчик WaitGroup после завершения функции
defer wg.Done()
// Выполняем HTTP-запрос
resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error fetching: %s\n", url)
return
}
defer resp.Body.Close()
// Читаем тело ответа
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response: %s\n", url)
return
}
// Выводим ответ
fmt.Printf("Response from %s: %s\n", url, string(body))
}(url)
}
// Ждем завершения всех goroutine
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment