mholt / curl-to-go

Convert curl commands to Go code in your browser

Home Page:https://mholt.github.io/curl-to-go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use http.DefaultClient to do requests

madislohmus opened this issue · comments

For GET, POST and HEAD http.Get(), http.Post(), http.Head() methods are used respectively here which internally use http.DefaultClient. I guess this is more of a suggestion, but why not use http.DefaultClient to do requests made with http.NewRequest also?

So instead of:

return 'req, err := http.NewRequest("'+method+'", "'+url+'", nil)\n'+err+'client := http.Client{}\nresp, err := client.Do(req)\n'+err+deferClose;

do

return 'req, err := http.NewRequest("'+method+'", "'+url+'", nil)\n'+err+'resp, err := http.DefaultClient.Do(req)\n'+err+deferClose;

and instead of:

// create the client and execute request
go += "\nclient := http.Client{}\nresp, err := client.Do(req)\n";

do

// create the client and execute request
go += "\nresp, err := http.DefaultClient.Do(req)\n";

Heh, I forgot about http.DefaultClient actually. But I wonder if leaving http.Client{} would be better so that the user can customize the client if they want to, without having to replace http.DefaultClient with their own. Just a thought.

True, might be better indeed. If that's the case though, it perhaps might make sense to refactor the renderSimple to just return the current last line of that method. The POST is a bit different actually since it adds empty string Content-Type header. Anyway it's not a bug and seems to be just matter of preference probably. Sorry, if it seems I made a fuss about nothing.

Cool tool 👍

Heh, no problem. It's good that we talk about different ideas and ways to have it work. I'll close this for now, but if anyone has more they'd like to add, that's totally fine!

IMO this should be re-opened until the change is applied.

@madislohmus said:

I guess this is more of a suggestion,

I don't agree. http.Client objects are meant to be long lived and not created on the fly, please don't encourage bad practices. From the documentation:

Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.

The documention for Get (and several other other methods) also suggests using DefaultClient:

To make a request with custom headers, use NewRequest and DefaultClient.Do.

If someone wants/needs to use their own client they'd already need to know how to change the simpler examples that use just http.Get. Doing a search/replace for http.DefaultClient to getMyClientFn(), or myGlobalClientVar, or whatever is trivial for those that wish to do so.

Okay, I've thought about this more today. It is better to present optimized code and let the user customize further if necessary, rather than assuming the user would want to customize it, even if it now requires one extra (trivial) step.