74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
|
|
namespace StellaOps.Cli.Services;
|
|
|
|
internal static class CliHttpClients
|
|
{
|
|
private const string CompatibilityClientName = "stellaops-cli.compat";
|
|
private static readonly SocketsHttpHandler SharedHandler = new()
|
|
{
|
|
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
|
|
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
|
|
PooledConnectionLifetime = TimeSpan.FromMinutes(15),
|
|
};
|
|
|
|
public static HttpClient CreateClient(
|
|
IServiceProvider services,
|
|
string? name = null,
|
|
Uri? baseAddress = null,
|
|
TimeSpan? timeout = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(services);
|
|
|
|
var factory = services.GetService<IHttpClientFactory>();
|
|
return CreateClient(factory, name, baseAddress, timeout);
|
|
}
|
|
|
|
public static HttpClient CreateClient(
|
|
IHttpClientFactory? factory = null,
|
|
string? name = null,
|
|
Uri? baseAddress = null,
|
|
TimeSpan? timeout = null)
|
|
{
|
|
var client = factory is null
|
|
? new HttpClient(SharedHandler, disposeHandler: false)
|
|
: factory.CreateClient(string.IsNullOrWhiteSpace(name) ? CompatibilityClientName : name);
|
|
|
|
Configure(client, baseAddress, timeout);
|
|
return client;
|
|
}
|
|
|
|
public static HttpClient CreateClient(
|
|
HttpMessageHandler handler,
|
|
Uri? baseAddress = null,
|
|
TimeSpan? timeout = null,
|
|
bool disposeHandler = true)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(handler);
|
|
|
|
var client = new HttpClient(handler, disposeHandler);
|
|
Configure(client, baseAddress, timeout);
|
|
return client;
|
|
}
|
|
|
|
private static void Configure(HttpClient client, Uri? baseAddress, TimeSpan? timeout)
|
|
{
|
|
if (baseAddress is not null)
|
|
{
|
|
client.BaseAddress = baseAddress;
|
|
}
|
|
|
|
if (timeout.HasValue)
|
|
{
|
|
client.Timeout = timeout.Value;
|
|
}
|
|
|
|
if (!client.DefaultRequestHeaders.UserAgent.Any())
|
|
{
|
|
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("StellaOps.Cli", "1.0"));
|
|
}
|
|
}
|
|
}
|