How to close the connection using Go client?

I normally connect to an elastic server, save the connection to a global variable, and reuse it in my entire app.

var es *elasticsearch.Client
 
func elasticConnect() {
  cfg := elasticsearch.Config{
          CloudID: "my_cloud_id",
          APIKey: "API_KEY"
  }
  var err error  
  es, err = elasticsearch.NewClient(cfg)

}

but sometimes I need to connect to another elastic instance and replace the global variable with the new one.
I want to know how close the old connection before making a new one (I looked in the documentation, but I couldn't find any method for closing the connections)

The Go client is stateless by nature hence why there is nothing like a close method since we do not keep a live connection to the server.
The rough idea is the client uses the information you provide both by config and by using the API to craft an HTTP requests which is then handled by the runtime.

You can control the underlying http.Transport by injecting it into the client's configuration within Transport and use that to close idle connections, it would still be up to you to stop existing request and prevent new ones during the swap.
You can find an example of this injection in this example.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.