h2non/gentleman

Thread Safety of Gentleman instance

sachin-walia opened this issue · 5 comments

I am wondering if one instance of Gentleman can be shared across multiple go-routines Or every go-routine should create it's own instance every time a request comes?

h2non commented

Thread safety is not fully built-in in the package, but global API surface, such as the middleware layer, should provide thread safety guarantees. However, gentleman's context does not, since every outoing request it's expected to be executed within a single coroutine context.

The typical approach here would be creating a new Request instance every time you want to perform a request.

Thanks @h2non. So if I create cli instance and share it then seems like it is fine:

//create once during server startup
cli := gentleman.New()

//create request in each go-routine
req := cli.Request()

Also If I want to setup middlewares / plugins (such as retry, headers, compression) for cli then it can be set globally as well?

h2non commented

Yes, you can. The middleware layer is hierarchical by design. You can register plugins at global level that would be executed on every outgoing request from that client. E.g:

cli := gentleman.New()
cli.Use(retry)
cli.Use(compression)

// Create request in each go-routine
req := cli.Request()

thanks @h2non this is very helpful.

h2non commented

Your welcome. I'm going to close the issue for now.