Skip to content

Commit 50894e9

Browse files
Use option monitor for configurating global and specific usages
1 parent 57394ec commit 50894e9

File tree

10 files changed

+136
-85
lines changed

10 files changed

+136
-85
lines changed

examples/HttpClientToCurl.Sample.InGlobal/Program.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
1-
using HttpClientToCurl.Config.Others;
21
using static HttpClientToCurl.Extensions.ServiceCollectionExtensions;
32

43
var builder = WebApplication.CreateBuilder(args);
54
builder.Services.AddControllers();
6-
builder.Services.AddHttpClientToCurl(config =>
7-
{
8-
config.ShowMode = ShowMode.Console | ShowMode.File;
9-
config.NeedAddDefaultHeaders = true;
10-
config.ConsoleEnableCodeBeautification = true;
11-
config.FileConfigPath = "C:\\Users\\Public";
12-
config.FileConfigFileName = "curl_commands";
13-
});
5+
6+
builder.Services.AddHttpClientToCurlInGeneralMode(builder.Configuration);
147
builder.Services.AddHttpClient();
158

169
var app = builder.Build();

examples/HttpClientToCurl.Sample.InGlobal/appsettings.json

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,23 @@
55
"Microsoft.AspNetCore": "Warning"
66
}
77
},
8-
"AllowedHosts": "*"
8+
"AllowedHosts": "*",
9+
"HttpClientToCurl": {
10+
"TurnOnAll": true,
11+
12+
"ShowOnConsole": {
13+
"TurnOn": true, //CAUTION: It will be applied when TurnOnAll is 'true'
14+
"NeedAddDefaultHeaders": true,
15+
"EnableCompression": false,
16+
"EnableCodeBeautification": true
17+
},
18+
19+
"SaveToFile": {
20+
"TurnOn": true, //CAUTION: It will be applied when TurnOnAll is 'true'
21+
"NeedAddDefaultHeaders": true,
22+
"EnableCompression": false,
23+
"Filename": "curl_commands",
24+
"Path": "C:\\Users\\Public"
25+
}
26+
}
927
}

examples/HttpClientToCurl.Sample.InSpecific/Controllers/MyController.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,19 @@ public class MyController(IHttpClientFactory httpClientFactory) : ControllerBase
99
{
1010
private readonly IHttpClientFactory _httpClientFactory = httpClientFactory;
1111

12-
[HttpGet]
12+
[HttpGet("send-and-show-curl")]
13+
public async Task SendAndShowCurl()
14+
{
15+
await SendRemoteRequest("my-client1");
16+
}
17+
18+
[HttpGet("send")]
1319
public async Task Send()
20+
{
21+
await SendRemoteRequest("my-client2");
22+
}
23+
24+
private async Task SendRemoteRequest(string httpClientName)
1425
{
1526
string apiUrl = "https://jsonplaceholder.typicode.com/posts";
1627

@@ -34,7 +45,7 @@ public async Task Send()
3445
// Use it to check and compare against all the requirements.
3546

3647
// Send the request
37-
HttpResponseMessage response = await _httpClientFactory.CreateClient("my-client").SendAsync(request);
48+
HttpResponseMessage response = await _httpClientFactory.CreateClient(httpClientName).SendAsync(request);
3849

3950
// Check if the request was successful (status code 200-299)
4051
if (response.IsSuccessStatusCode)

examples/HttpClientToCurl.Sample.InSpecific/Program.cs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,11 @@
1-
using HttpClientToCurl.Config.Others;
2-
using HttpClientToCurl.HttpMessageHandlers;
31
using static HttpClientToCurl.Extensions.ServiceCollectionExtensions;
42

53
var builder = WebApplication.CreateBuilder(args);
64
builder.Services.AddControllers();
7-
builder.Services.AddHttpClientToCurl(config =>
8-
{
9-
config.ShowMode = ShowMode.Console | ShowMode.File;
10-
config.NeedAddDefaultHeaders = true;
11-
config.ConsoleEnableCodeBeautification = true;
12-
config.FileConfigPath = "C:\\Users\\Public";
13-
config.FileConfigFileName = "curl_commands";
14-
}, false);
15-
builder.Services.AddHttpClient("my-client")
16-
.AddHttpMessageHandler<CurlGeneratorHttpMessageHandler>();
5+
6+
builder.Services.AddHttpClientToCurl(builder.Configuration);
7+
builder.Services.AddHttpClient("my-client1", showCurl: true);
8+
builder.Services.AddHttpClient("my-client2");
179

1810
var app = builder.Build();
1911

examples/HttpClientToCurl.Sample.InSpecific/appsettings.json

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,23 @@
55
"Microsoft.AspNetCore": "Warning"
66
}
77
},
8-
"AllowedHosts": "*"
8+
"AllowedHosts": "*",
9+
"HttpClientToCurl": {
10+
"TurnOnAll": true,
11+
12+
"ShowOnConsole": {
13+
"TurnOn": true, //CAUTION: It will be applied when TurnOnAll is 'true'
14+
"NeedAddDefaultHeaders": true,
15+
"EnableCompression": false,
16+
"EnableCodeBeautification": true
17+
},
18+
19+
"SaveToFile": {
20+
"TurnOn": true, //CAUTION: It will be applied when TurnOnAll is 'true'
21+
"NeedAddDefaultHeaders": true,
22+
"EnableCompression": false,
23+
"Filename": "curl_commands",
24+
"Path": "C:\\Users\\Public"
25+
}
26+
}
927
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
namespace HttpClientToCurl.Config;
2+
3+
public sealed class CompositConfig
4+
{
5+
/// <summary>
6+
/// Set true to create curl output; false to disable it. <c>Default is true</c>.
7+
/// </summary>
8+
public bool TurnOnAll { get; set; } = true;
9+
10+
/// <summary>
11+
/// Set true to show curl on the console; false to disable it. <c>Default is true</c>.
12+
/// <para>If TurnOnAll is set to false, it will be ignored.</para>
13+
/// </summary>
14+
public ConsoleConfig ShowOnConsole { get; set; }
15+
16+
/// <summary>
17+
/// Set true to save the curl file; false to disable it. <c>Default is true</c>.
18+
/// <para>If TurnOnAll is set to false, it will be ignored.</para>
19+
/// </summary>
20+
public FileConfig SaveToFile { get; set; }
21+
}

src/HttpClientToCurl/Config/GlobalConfig.cs

Lines changed: 0 additions & 27 deletions
This file was deleted.
Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using HttpClientToCurl.Config;
2-
using HttpClientToCurl.Config.Others;
32
using HttpClientToCurl.HttpMessageHandlers;
3+
using Microsoft.Extensions.Configuration;
44
using Microsoft.Extensions.DependencyInjection;
55
using Microsoft.Extensions.Http;
66

@@ -9,27 +9,44 @@ namespace HttpClientToCurl.Extensions;
99
public static class ServiceCollectionExtensions
1010
{
1111
/// <summary>
12-
/// Generating curl script of all HTTP requests.
12+
/// Generating curl script for all HTTP requests.
1313
/// <para> By default, show it in the IDE console. </para>
1414
/// </summary>
15-
/// <param name="configAction">Optional</param>
16-
/// <param name="isGlobal">Apply for all http requests in the application or not. Default is true.</param>
17-
public static void AddHttpClientToCurl(
18-
this IServiceCollection services,
19-
Action<GlobalConfig> configAction = null,
20-
bool isGlobal = true)
15+
public static void AddHttpClientToCurlInGeneralMode(
16+
this IServiceCollection services,
17+
IConfiguration configuration)
2118
{
22-
configAction ??= config => config.ShowMode = ShowMode.Console;
19+
AddServices(services, configuration);
20+
services.Add(ServiceDescriptor.Transient<IHttpMessageHandlerBuilderFilter, HttpMessageHandlerAppender>());
21+
}
2322

24-
var config = new GlobalConfig();
25-
configAction?.Invoke(config);
23+
/// <summary>
24+
/// Generating curl script for specific http client
25+
/// </summary>
26+
/// <param name="services"></param>
27+
/// <param name="configuration"></param>
28+
public static void AddHttpClientToCurl(
29+
this IServiceCollection services,
30+
IConfiguration configuration)
31+
{
32+
AddServices(services, configuration);
33+
}
2634

27-
services.AddSingleton(config);
28-
services.AddTransient<CurlGeneratorHttpMessageHandler>();
35+
public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, bool showCurl = false)
36+
{
37+
var httpClientBuilder = HttpClientFactoryServiceCollectionExtensions.AddHttpClient(services, name);
2938

30-
if (isGlobal)
39+
if (showCurl)
3140
{
32-
services.Add(ServiceDescriptor.Transient<IHttpMessageHandlerBuilderFilter, HttpMessageHandlerAppender>());
41+
httpClientBuilder.AddHttpMessageHandler<CurlGeneratorHttpMessageHandler>();
3342
}
43+
44+
return httpClientBuilder;
45+
}
46+
47+
private static void AddServices(IServiceCollection services, IConfiguration configuration)
48+
{
49+
services.Configure<CompositConfig>(configuration.GetSection("HttpClientToCurl"));
50+
services.AddTransient<CurlGeneratorHttpMessageHandler>();
3451
}
3552
}

src/HttpClientToCurl/HttpClientToCurl.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
<ItemGroup>
2626
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.10" />
2727
<PackageReference Include="Microsoft.Extensions.Http" Version="9.0.10" />
28+
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.10" />
2829
</ItemGroup>
2930

3031
</Project>

src/HttpClientToCurl/HttpMessageHandlers/CurlGeneratorHttpMessageHandler.cs

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,42 @@
11
using HttpClientToCurl.Config;
2-
using HttpClientToCurl.Config.Others;
32
using HttpClientToCurl.Extensions;
3+
using Microsoft.Extensions.Options;
44

55
namespace HttpClientToCurl.HttpMessageHandlers;
66

7-
public class CurlGeneratorHttpMessageHandler(GlobalConfig config) : DelegatingHandler
7+
public class CurlGeneratorHttpMessageHandler(IOptionsMonitor<CompositConfig> monitorConfig) : DelegatingHandler
88
{
9+
private readonly IOptionsMonitor<CompositConfig> _monitorConfig = monitorConfig;
10+
911
protected override Task<HttpResponseMessage> SendAsync(
1012
HttpRequestMessage httpRequestMessage,
1113
CancellationToken cancellationToken)
1214
{
13-
if (config.ShowMode.HasFlag(ShowMode.Console))
15+
var config = _monitorConfig.CurrentValue;
16+
if (config.TurnOnAll)
1417
{
15-
httpRequestMessage.GenerateCurlInConsole(httpRequestMessage.RequestUri, consoleConfig =>
18+
if (config.ShowOnConsole.TurnOn)
1619
{
17-
consoleConfig.TurnOn = true;
18-
consoleConfig.EnableCodeBeautification = config.ConsoleEnableCodeBeautification;
19-
consoleConfig.EnableCompression = config.ConsoleEnableCompression;
20-
consoleConfig.NeedAddDefaultHeaders = config.NeedAddDefaultHeaders;
21-
});
22-
}
20+
httpRequestMessage.GenerateCurlInConsole(httpRequestMessage.RequestUri, consoleConfig =>
21+
{
22+
consoleConfig.TurnOn = true;
23+
consoleConfig.EnableCodeBeautification = config.ShowOnConsole.EnableCodeBeautification;
24+
consoleConfig.EnableCompression = config.ShowOnConsole.EnableCompression;
25+
consoleConfig.NeedAddDefaultHeaders = config.ShowOnConsole.NeedAddDefaultHeaders;
26+
});
27+
}
2328

24-
if (config.ShowMode.HasFlag(ShowMode.File))
25-
{
26-
httpRequestMessage.GenerateCurlInFile(httpRequestMessage.RequestUri, fileConfig =>
29+
if (config.SaveToFile.TurnOn)
2730
{
28-
fileConfig.TurnOn = true;
29-
fileConfig.Filename = config.FileConfigFileName;
30-
fileConfig.Path = config.FileConfigPath;
31-
fileConfig.NeedAddDefaultHeaders = config.NeedAddDefaultHeaders;
32-
});
31+
httpRequestMessage.GenerateCurlInFile(httpRequestMessage.RequestUri, fileConfig =>
32+
{
33+
fileConfig.TurnOn = true;
34+
fileConfig.EnableCompression = config.SaveToFile.EnableCompression;
35+
fileConfig.NeedAddDefaultHeaders = config.SaveToFile.NeedAddDefaultHeaders;
36+
fileConfig.Path = config.SaveToFile.Path;
37+
fileConfig.Filename = config.SaveToFile.Filename;
38+
});
39+
}
3340
}
3441

3542
var response = base.SendAsync(httpRequestMessage, cancellationToken);

0 commit comments

Comments
 (0)