Skip to content

Commit 1c3b76b

Browse files
authored
Merge pull request #7 from mxritzdev/refactor
Cleaned up the project
2 parents cae5134 + 360598e commit 1c3b76b

File tree

5 files changed

+145
-94
lines changed

5 files changed

+145
-94
lines changed
Lines changed: 7 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,30 @@
11
using LinkRouter.App.Configuration;
2+
using LinkRouter.App.Services;
23
using Microsoft.AspNetCore.Mvc;
3-
using Prometheus;
4-
54

65
namespace LinkRouter.App.Http.Controllers;
76

87
[ApiController]
98
public class RedirectController : Controller
109
{
11-
1210
private readonly Config Config;
13-
14-
private readonly Counter RouteCounter = Metrics.CreateCounter(
15-
"linkrouter_requests",
16-
"Counts the number of requests to the link router",
17-
new CounterConfiguration
18-
{
19-
LabelNames = new[] { "route" }
20-
}
21-
);
22-
23-
24-
private readonly Counter NotFoundCounter = Metrics.CreateCounter(
25-
"linkrouter_404_requests",
26-
"Counts the number of not found requests to the link router",
27-
new CounterConfiguration
28-
{
29-
LabelNames = new[] { "route" }
30-
}
31-
);
11+
private readonly RedirectionService RedirectionService;
3212

33-
public RedirectController(Config config)
13+
public RedirectController(Config config, RedirectionService redirectionService)
3414
{
3515
Config = config;
16+
RedirectionService = redirectionService;
3617
}
3718

3819
[HttpGet("/{*path}")]
3920
public async Task<ActionResult> RedirectToExternalUrl(string path)
4021
{
41-
if (!path.EndsWith("/"))
42-
path += "/";
43-
44-
path = "/" + path;
45-
46-
Console.WriteLine(path);
47-
48-
var redirectRoute = Config.CompiledRoutes?.FirstOrDefault(x => x.CompiledPattern.IsMatch(path));
49-
50-
if (redirectRoute == null)
51-
{
52-
NotFoundCounter
53-
.WithLabels(path)
54-
.Inc();
55-
56-
if (Config.NotFoundBehavior.RedirectOn404)
57-
if (Config.ErrorCodePattern.IsMatch(Config.NotFoundBehavior.RedirectUrl))
58-
{
59-
var errorCodeMatch = Config.ErrorCodePattern.Match(Config.NotFoundBehavior.RedirectUrl);
60-
var errorCode = int.Parse(errorCodeMatch.Groups[1].Value);
61-
return StatusCode(errorCode);
62-
} else
63-
return Redirect(Config.NotFoundBehavior.RedirectUrl);
64-
65-
return NotFound();
66-
}
67-
68-
var match = redirectRoute.CompiledPattern.Match(path);
69-
70-
string redirectUrl = redirectRoute.RedirectUrl;
71-
72-
if (Config.ErrorCodePattern.IsMatch(redirectUrl))
73-
{
74-
var errorCodeMatch = Config.ErrorCodePattern.Match(redirectUrl);
75-
var errorCode = int.Parse(errorCodeMatch.Groups[1].Value);
76-
return StatusCode(errorCode);
77-
}
78-
79-
foreach (var placeholder in redirectRoute.Placeholders)
80-
{
81-
var value = match.Groups[placeholder.Value].Value;
82-
redirectUrl = redirectUrl.Replace("{" + placeholder.Key + "}", value);
83-
}
84-
85-
return Redirect(redirectUrl);
22+
return await RedirectionService.GetRedirect(path);
8623
}
8724

8825
[HttpGet("/")]
89-
public IActionResult GetRootRoute()
26+
public async Task<ActionResult> GetRootRoute()
9027
{
91-
RouteCounter
92-
.WithLabels("/")
93-
.Inc();
94-
95-
string url = Config.RootRoute;
96-
97-
if (Config.ErrorCodePattern.IsMatch(url))
98-
{
99-
var errorCodeMatch = Config.ErrorCodePattern.Match(url);
100-
var errorCode = int.Parse(errorCodeMatch.Groups[1].Value);
101-
return StatusCode(errorCode);
102-
}
103-
104-
return Redirect(url);
28+
return await RedirectionService.GetRedirect(string.Empty);
10529
}
10630
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using MoonCore.Attributes;
2+
using Prometheus;
3+
4+
namespace LinkRouter.App.Services;
5+
6+
[Singleton]
7+
public class MetricsService
8+
{
9+
private readonly Counter RouteCounter = Metrics.CreateCounter(
10+
"linkrouter_requests",
11+
"Counts the number of requests to the link router",
12+
new CounterConfiguration
13+
{
14+
LabelNames = new[] { "route" }
15+
}
16+
);
17+
18+
19+
private readonly Counter NotFoundCounter = Metrics.CreateCounter(
20+
"linkrouter_404_requests",
21+
"Counts the number of not found requests to the link router",
22+
new CounterConfiguration
23+
{
24+
LabelNames = new[] { "route" }
25+
}
26+
);
27+
28+
public Task IncrementNotFound(string path)
29+
{
30+
NotFoundCounter
31+
.WithLabels(path)
32+
.Inc();
33+
34+
return Task.CompletedTask;
35+
}
36+
37+
public Task IncrementFound(string path)
38+
{
39+
RouteCounter
40+
.WithLabels(path)
41+
.Inc();
42+
43+
return Task.CompletedTask;
44+
}
45+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
using LinkRouter.App.Configuration;
2+
using Microsoft.AspNetCore.Mvc;
3+
using MoonCore.Attributes;
4+
5+
namespace LinkRouter.App.Services;
6+
7+
[Singleton]
8+
public class RedirectionService
9+
{
10+
private readonly Config Config;
11+
private readonly MetricsService MetricsService;
12+
13+
public RedirectionService(Config config, MetricsService metricsService)
14+
{
15+
Config = config;
16+
MetricsService = metricsService;
17+
}
18+
19+
public async Task<ActionResult> GetRedirect(string path)
20+
{
21+
if (path == "")
22+
{
23+
var url = Config.RootRoute;
24+
25+
if (TryGetErrorCode(url, out var notFoundStatusCode))
26+
return new StatusCodeResult(notFoundStatusCode);
27+
28+
await MetricsService.IncrementFound("/");
29+
30+
return new RedirectResult(url);
31+
}
32+
33+
if (!path.EndsWith("/"))
34+
path += "/";
35+
36+
path = "/" + path;
37+
38+
39+
var redirectRoute = Config.CompiledRoutes?.FirstOrDefault(x => x.CompiledPattern.IsMatch(path));
40+
41+
42+
if (redirectRoute == null)
43+
{
44+
await MetricsService.IncrementNotFound(path);
45+
46+
if (!Config.NotFoundBehavior.RedirectOn404)
47+
return new NotFoundResult();
48+
49+
50+
if (TryGetErrorCode(Config.NotFoundBehavior.RedirectUrl, out var notFoundStatusCode))
51+
return new StatusCodeResult(notFoundStatusCode);
52+
53+
return new RedirectResult(Config.NotFoundBehavior.RedirectUrl);
54+
}
55+
56+
var match = redirectRoute.CompiledPattern.Match(path);
57+
58+
if (TryGetErrorCode(redirectRoute.RedirectUrl, out var statusCode))
59+
return new StatusCodeResult(statusCode);
60+
61+
62+
foreach (var placeholder in redirectRoute.Placeholders)
63+
{
64+
var value = match.Groups[placeholder.Value].Value;
65+
redirectRoute.RedirectUrl = redirectRoute.RedirectUrl.Replace("{" + placeholder.Key + "}", value);
66+
}
67+
68+
await MetricsService.IncrementFound(path);
69+
70+
return new RedirectResult(redirectRoute.RedirectUrl);
71+
}
72+
73+
private bool TryGetErrorCode(string url, out int code)
74+
{
75+
if (Config.ErrorCodePattern.IsMatch(url))
76+
{
77+
var errorCodeMatch = Config.ErrorCodePattern.Match(url);
78+
code = int.Parse(errorCodeMatch.Groups[1].Value);
79+
return true;
80+
}
81+
82+
code = 0;
83+
84+
return false;
85+
}
86+
}

LinkRouter/LinkRouter.csproj

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@
99
</PropertyGroup>
1010

1111
<ItemGroup>
12-
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.20"/>
13-
<PackageReference Include="MoonCore" Version="1.5.4" />
12+
<PackageReference Include="MoonCore" Version="2.0.6" />
1413
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" />
15-
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
1614
</ItemGroup>
1715

1816
<ItemGroup>

LinkRouter/Program.cs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using LinkRouter.App.Services;
44
using MoonCore.Extensions;
55
using MoonCore.Helpers;
6+
using MoonCore.Logging;
67
using Prometheus;
78

89
namespace LinkRouter;
@@ -13,18 +14,13 @@ public static void Main(string[] args)
1314
{
1415
var builder = WebApplication.CreateBuilder(args);
1516

16-
Directory.CreateDirectory(PathBuilder.Dir("data"));
17+
Directory.CreateDirectory(Path.Combine("data"));
1718

1819
builder.Services.AddControllers();
1920

20-
var loggerProviders = LoggerBuildHelper.BuildFromConfiguration(configuration =>
21-
{
22-
configuration.Console.Enable = true;
23-
configuration.Console.EnableAnsiMode = true;
24-
});
25-
2621
builder.Logging.ClearProviders();
27-
builder.Logging.AddProviders(loggerProviders);
22+
23+
builder.Logging.AddAnsiConsole();
2824

2925
builder.Services.AddHostedService<ConfigWatcher>();
3026

@@ -42,6 +38,8 @@ public static void Main(string[] args)
4238
JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }));
4339

4440
builder.Services.AddSingleton(config);
41+
42+
builder.Services.AutoAddServices<Program>();
4543

4644
builder.Services.AddMetricServer(options => { options.Port = 5000; });
4745

0 commit comments

Comments
 (0)