...

/

Building a Network Package—Client Pool

Building a Network Package—Client Pool

Learn how to build a self-sufficient network package.

We will build a well-rounded network package that will serve a wide variety of our needs. This package should be easy to use throughout our code whenever and wherever we want to make HTTP requests. It should be efficient, have a clean, elegant API, and be extensible.

Network client wrapper

Just arbitrarily making HTTP calls throughout our codebase can get ugly and unmaintainable quickly, especially when we want different configurations for different API calls. Let’s set up an actual client type that can take care of our configurations and allow us to perform network actions on top of it.

type httpClient struct {
headers http.Header
body io.Reader
timeout int
clientName string
}
Basic HTTP client type

But is this client type enough? This struct doesn’t actually seem to contain a member of the http.Client type! But this is done on purpose. An HTTP client does not need to be reinstantiated whenever we make a network call. That would be very inefficient and unnecessary because one HTTP client is more than capable of handling multiple calls efficiently. Therefore, we will only create new instances of the underlying client when we want a different configuration with time-outs or custom transports. However, the custom type we create might be instantiated on the fly and called from various places in our code whenever and wherever we want ...