Aleksandr Dorofeev
Aleksandr Dorofeev

Reputation: 71

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

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?

Upvotes: 0

Views: 1308

Answers (1)

Faruqi Ikhsan
Faruqi Ikhsan

Reputation: 36

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()
}

Upvotes: 2

Related Questions