Last active
January 9, 2024 11:57
-
-
Save lissdy/65a2766f23384db7c63caf4e45b30c6d to your computer and use it in GitHub Desktop.
Golang send multiple requests
This file contains hidden or 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 ( | |
"net/http" | |
"fmt" | |
"time" | |
"sync" | |
) | |
func main() { | |
start := time.Now() | |
var urls = []string{ | |
"https://github.com/appleboy/gorush", | |
"https://github.com/gin-gonic/gin", | |
"https://github.com/astaxie/beego", | |
"https://github.com/helm/helm", | |
"https://github.com/argoproj/argo-cd", | |
} | |
checkURLs(urls) | |
fmt.Printf("%.2fs elapsed", time.Since(start).Seconds()) | |
} | |
func checkURLs(urls []string) { | |
var wg sync.WaitGroup | |
c := make(chan string) | |
for _, url := range urls { | |
wg.Add(1) | |
go checkURL(url, c, &wg) | |
} | |
go func() { | |
wg.Wait() | |
close(c) | |
}() | |
for msg := range c { | |
fmt.Println(msg) | |
} | |
} | |
func checkURL(url string, c chan string, wg *sync.WaitGroup) { | |
defer (*wg).Done() | |
_, err := http.Get(url) | |
if err != nil { | |
c <- url + " can not be reached" | |
} else { | |
c <- url + " can be reached" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment