Skip to content

Commit

Permalink
Add PrefersColorSchemeMiddleware and config setting
Browse files Browse the repository at this point in the history
- Added `PrefersColorSchemeMiddleware` to handle color scheme headers.
- Updated `Program.cs` to conditionally use the new middleware based on `Experimental:UsePrefersColorSchemeHeader` setting.
- Modified `appsettings.json` to include `Experimental` section with `UsePrefersColorSchemeHeader` setting.
  • Loading branch information
EdiWang committed Oct 8, 2024
1 parent 2e84983 commit 1814843
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Moonglade.Web/Middleware/PrefersColorSchemeMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Moonglade.Web.Middleware;

public class PrefersColorSchemeMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
context.Response.OnStarting(() =>
{
context.Response.Headers["Accept-CH"] = "Sec-CH-Prefers-Color-Scheme";
context.Response.Headers["Vary"] = "Sec-CH-Prefers-Color-Scheme";
context.Response.Headers["Critical-CH"] = "Sec-CH-Prefers-Color-Scheme";
return Task.CompletedTask;
});

await next(context);
}
}
5 changes: 5 additions & 0 deletions src/Moonglade.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,11 @@ private static void ConfigureMiddleware(WebApplication app, List<CultureInfo> cu
options.IconFilePath = "/favicon-16x16.png";
});

// In v14.11.0, just send the header to the client in order to observe browser behaviour
// We will read client's preference in future versions
bool usePrefersColorSchemeHeader = app.Configuration.GetSection("Experimental:UsePrefersColorSchemeHeader").Get<bool>();
if (usePrefersColorSchemeHeader) app.UseMiddleware<PrefersColorSchemeMiddleware>();

app.UseMiddleware<PoweredByMiddleware>();
app.UseMiddleware<DNTMiddleware>();

Expand Down
3 changes: 3 additions & 0 deletions src/Moonglade.Web/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@
"SetLastModifiedHeader": true,
"CacheMinutes": 20
},
"Experimental": {
"UsePrefersColorSchemeHeader": true
},
"Logging": {
"LogLevel": {
"Default": "Warning",
Expand Down

0 comments on commit 1814843

Please sign in to comment.