Stabilize web test lane warning cleanup
This commit is contained in:
73
src/Cli/StellaOps.Cli/Services/CliHttpClients.cs
Normal file
73
src/Cli/StellaOps.Cli/Services/CliHttpClients.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user