Junior — Senior
Parallel request to the list of URLs
livecode
Task condition
Example of a program demonstrating simultaneous sending of HTTP requests to a set of websites. First, an array of links is formed, then a separate goroutine is launched for each link, which outputs the start and end status of the request. After launching all goroutines, the main thread outputs a message, waits for a short pause, and then terminates.
The program output may look like this:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
links := []string{
"https://www.lamoda.ru",
"https://www.yandex.ru",
"https://www.mail.ru",
"https://www.google.com",
}
for _, link := range links {
go func(l string) {
fmt.Printf("Fetching %s...\n", l)
err := getURL(l)
if err != nil {
fmt.Printf("Error fetching %s: %v\n", l, err)
return
}
fmt.Printf("Fetched %s\n", l)
}(link)
}
fmt.Println("All requests launched!")
time.Sleep(400 * time.Millisecond)
fmt.Println("Program finished.")
}
func getURL(address string) error {
// Detailed implementation is omitted
_, err := http.Get(address)
return err
}