Created
May 13, 2023 12:08
-
-
Save EvilFreelancer/025601bf5f37da46d0653784e4434bd4 to your computer and use it in GitHub Desktop.
Асинхронная загрузка ссылок (кравлер) Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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