algorithms-go/other/等待goroutine完成/main.go
2021-04-07 14:27:14 +08:00

36 lines
593 B
Go

package main
import (
"fmt"
"net/http"
"sync"
)
func main() {
fmt.Println("start...")
var urls = []string{
"https://www.baidu.com/",
"https://www.cnblogs.com/",
"https://www.oschina.net/",
}
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go fetch(&wg, url)
}
wg.Wait()
fmt.Println("...end")
}
// fetch
func fetch(wg *sync.WaitGroup, url string) (string, error) {
defer wg.Done()
response, err := http.Get(url)
if err != nil {
return "", err
}
fmt.Println(fmt.Sprintf("request %s - response %s", url, response.Status))
return response.Status, nil
}