golang http.Get request works usual way, but do not work inside go routines

Issue

I have some server working with GET requests. Need to create highload for this server
Simple test client:

func main(){
    http.Get("http://localhost:8080/8")
}

It works, server show that he received request

Another test:

func main(){
    for i:=0; i<5; i++{
        go func() {
            http.Get("http://localhost:8080/8")
        }()
    }
}

or even

func main(){
    for i:=0; i<5; i++{
        go http.Get("http://localhost:8080/8")
    }
}

It didn’t work, server did not receiving any requests

So, what is a problem?

Solution

I think it’s because your application terminated right after your loop end.

to handle this you can use WaitGroup. and change your code to be like this:

func main(){

    wg := sync.Waitgroup{}

    for i:=0; i<5; i++{
        wg.Add(1)
        go func() {
            defer wg.Done()
            http.Get("http://localhost:8080/8")
        }()
    }

    wg.Wait()
}

Answered By – Faruqi Ikhsan

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.