Are there any benefits in using go routine on remote server calls in API handler?

Suppose I have a login handler and I am using Cloudflare’s Turnstile. I receive a token from client and then verify it against cloudflare’s server then return respective response back. However, I was wondering if there are any performance gain from this or not.

Non-concurrent

func handleLogin(w http.ResponseWriter, r *http.Request) {
	// some code

	isValid:=turnstile.Verify(token)

	// reply related code
}

Concurrent

func handleLogin(w http.ResponseWriter, r *http.Request) {
	// some code

	var ch = make(chan bool)

	go func ()  {
		ch <- turnstile.Verify(token)
	}()

	select {
	case <-ch:
		// stuffs
	}
	

	// reply related code
}

Not as you have it, because you’re not doing any other work. So you’re just blocking the current thread waiting for the verify thread to finish, no advantage over having them both in the same thread.

1 Like

no more difference, both ways are in the same thread.
if you want to have an efficient way, you can
start another gorouting to receive login requests, in your handle logic just send a message to the gorouting,
concept as below:



type HttpRequest struct{
    w http.ResonseWriter,
    r * http.Request,
}
var chVerify =  make(chan HttpRequest,1000)
func verifyLogin() {
       for {
         select {
            case ch <- chVerfiy:
                 turnstile.Verify(ch.r.getToken)
                 Response to w ...
                 
         }
     }
}

in your main.go 
start it :
go verifyLogin()

in your handler:
func handleLogin(w http.ResponseWriter, r *http.Request) {
 go func() {
       chVerify <- HttpRequest{w,r}
    }
}

1 Like