refactor(http): refactor http client to accept more customisable options (#2414)

refactor(http): refactor http client to take options struct

This commit updates the arguments for the `CreateHTTPClient`
function to consume a struct which can be extended as required.
It replaces the certPath argument with a struct of 3 paths for
client ertificate, client key, and ca cert. It also adds
a TLSEnabled option for when an HTTP Client is required
without any further TLS config.

Existing consumers of this function have been updated so that
they can work as they do today. This change is a no-op for
existing features.

This allows for certificate paths to be customised and
allows other modules to re-use the same HTTP client and get
the benefits of mTLS support and per-host certificates.

Signed-off-by: Vishwas Rajashekar <vrajashe@cisco.com>
This commit is contained in:
Vishwas R
2024-05-07 02:13:41 +05:30
committed by GitHub
parent 4671e412fc
commit be5ad66797
5 changed files with 216 additions and 29 deletions
+21 -1
View File
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
@@ -114,7 +115,26 @@ func (httpClient *Client) SetConfig(config Config) error {
httpClient.url = clientURL
client, err := common.CreateHTTPClient(config.TLSVerify, clientURL.Host, config.CertDir)
clientOpts := common.HTTPClientOptions{
// we want TLS enabled when verifyTLS is true.
TLSEnabled: config.TLSVerify,
VerifyTLS: config.TLSVerify,
Host: clientURL.Host,
}
if config.CertDir != "" {
// only configure the default cert file names if the CertDir was specified.
clientOpts.CertOptions = common.HTTPClientCertOptions{
// filepath is the recommended library to use for joining paths
// taking into account the underlying OS.
// ref: https://stackoverflow.com/a/39182128
ClientCertFile: filepath.Join(config.CertDir, common.ClientCertFilename),
ClientKeyFile: filepath.Join(config.CertDir, common.ClientKeyFilename),
RootCaCertFile: filepath.Join(config.CertDir, common.CaCertFilename),
}
}
client, err := common.CreateHTTPClient(&clientOpts)
if err != nil {
return err
}