-
-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
Showing
10 changed files
with
985 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
|
||
<TargetFrameworks>net8.0;net9.0</TargetFrameworks> | ||
|
||
<LangVersion>13.0</LangVersion> | ||
<Nullable>enable</Nullable> | ||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
|
||
<AssemblyVersion>9.3.0.0</AssemblyVersion> | ||
<FileVersion>9.3.0.0</FileVersion> | ||
<Version>9.3.0</Version> | ||
|
||
<Authors>Andreas Nägeli, Martin Maťátko</Authors> | ||
<Company /> | ||
|
||
<PackageLicenseFile>LICENSE</PackageLicenseFile> | ||
<PackageProjectUrl>https://genhttp.org/</PackageProjectUrl> | ||
|
||
<Description>Allows to handle requests in a culture specific manner.</Description> | ||
<PackageTags>HTTP Webserver C# Module i18n</PackageTags> | ||
|
||
<PublishRepositoryUrl>true</PublishRepositoryUrl> | ||
<IncludeSymbols>true</IncludeSymbols> | ||
<SymbolPackageFormat>snupkg</SymbolPackageFormat> | ||
|
||
<GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
<NoWarn>CS1591,CS1587,CS1572,CS1573</NoWarn> | ||
|
||
<PackageIcon>icon.png</PackageIcon> | ||
|
||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
|
||
<None Include="..\..\LICENSE" Pack="true" PackagePath="\" /> | ||
<None Include="..\..\Resources\icon.png" Pack="true" PackagePath="\" /> | ||
|
||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\API\GenHTTP.Api.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
using System.Globalization; | ||
using GenHTTP.Modules.I18n.Provider; | ||
|
||
namespace GenHTTP.Modules.I18n; | ||
|
||
public static class Localization | ||
{ | ||
#region Builder | ||
|
||
/// <summary> | ||
/// Creates a localization handler that parses and sets | ||
/// <see cref="CultureInfo"/> based on defined rules. | ||
/// </summary> | ||
/// <returns>By default culture is read from request header | ||
/// and is set to <see cref=" CultureInfo.CurrentUICulture"/>.</returns> | ||
public static LocalizationConcernBuilder Create() => new(); | ||
|
||
#endregion | ||
} |
139 changes: 139 additions & 0 deletions
139
Modules/GenHTTP.Modules.I18n/Parsers/CultureInfoParser.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
using System.Buffers; | ||
using System.Globalization; | ||
|
||
namespace GenHTTP.Modules.I18n.Parsers; | ||
|
||
public static class CultureInfoParser | ||
{ | ||
private static readonly Comparer<(string Language, double Quality)> QualityComparer = | ||
Comparer<(string Language, double Quality)>.Create((a, b) => b.Quality.CompareTo(a.Quality)); | ||
|
||
/// <summary> | ||
/// Parses the given language header (e.g. from Accept-Language) into an array of CultureInfo, | ||
/// sorted by their quality values in descending order. If no valid languages are found, | ||
/// returns an empty array. | ||
/// | ||
/// Specification: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language | ||
/// | ||
/// This implementation uses ArrayPool to minimize allocations. | ||
/// </summary> | ||
/// <param name="language">The language header string to parse.</param> | ||
/// <returns>An array of <see cref="CultureInfo"/> objects parsed from the input string.</returns> | ||
public static CultureInfo[] ParseFromLanguage(string? language) | ||
{ | ||
if (string.IsNullOrWhiteSpace(language)) | ||
{ | ||
return []; | ||
} | ||
|
||
var span = language.AsSpan().Trim(); | ||
if (span.IsEmpty) | ||
{ | ||
return []; | ||
} | ||
|
||
// Count how many segments (comma-delimited) | ||
var count = 1; | ||
for (int i = 0; i < span.Length; i++) | ||
{ | ||
if (span[i] == ',') count++; | ||
} | ||
|
||
var pool = ArrayPool<(string Language, double Quality)>.Shared; | ||
(string Language, double Quality)[] rentedArray = pool.Rent(count); | ||
|
||
try | ||
{ | ||
var actualCount = 0; | ||
var start = 0; | ||
int commaIndex; | ||
do | ||
{ | ||
commaIndex = span[start..].IndexOf(','); | ||
ReadOnlySpan<char> segment; | ||
if (commaIndex >= 0) | ||
{ | ||
segment = span.Slice(start, commaIndex).Trim(); | ||
start += commaIndex + 1; | ||
} | ||
else | ||
{ | ||
segment = span[start..].Trim(); | ||
} | ||
|
||
if (!segment.IsEmpty) | ||
{ | ||
// segment format: "lang[-region][;q=...]" or just "lang[-region]" | ||
var semicolonIndex = segment.IndexOf(';'); | ||
var qValue = 1d; | ||
ReadOnlySpan<char> languagePart; | ||
|
||
if (semicolonIndex >= 0) | ||
{ | ||
languagePart = segment[..semicolonIndex].Trim(); | ||
var afterSemicolon = segment[(semicolonIndex + 1)..].Trim(); | ||
|
||
// afterSemicolon should look like "q=0.5" | ||
if (afterSemicolon.StartsWith("q=", StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
var qSpan = afterSemicolon[2..].Trim(); // skip 'q=' | ||
if (!double.TryParse(qSpan, NumberStyles.Number, CultureInfo.InvariantCulture, out qValue)) | ||
{ | ||
qValue = 1; | ||
} | ||
} | ||
} | ||
else | ||
{ | ||
languagePart = segment; | ||
} | ||
|
||
if (!languagePart.IsEmpty && actualCount < rentedArray.Length) | ||
{ | ||
// Convert languagePart to string only once here | ||
rentedArray[actualCount++] = (languagePart.ToString(), qValue); | ||
} | ||
} | ||
} while (commaIndex >= 0); | ||
|
||
if (actualCount == 0) | ||
{ | ||
return []; | ||
} | ||
|
||
// Sort by quality descending | ||
Array.Sort(rentedArray, 0, actualCount, QualityComparer); | ||
|
||
// Convert to CultureInfo array and return rented array | ||
List<CultureInfo> results = new(actualCount); | ||
|
||
for (int i = 0; i < actualCount; i++) | ||
{ | ||
var (lang, _) = rentedArray[i]; | ||
if (string.IsNullOrWhiteSpace(lang)) | ||
{ | ||
continue; | ||
} | ||
|
||
try | ||
{ | ||
var parsed = CultureInfo.CreateSpecificCulture(lang); | ||
if (parsed.LCID != CultureInfo.InvariantCulture.LCID) | ||
{ | ||
results.Add(parsed); | ||
} | ||
} | ||
catch (CultureNotFoundException) | ||
{ | ||
// skip invalid cultures | ||
} | ||
} | ||
|
||
return results.Count > 0 ? [.. results] : []; | ||
} | ||
finally | ||
{ | ||
pool.Return(rentedArray); | ||
} | ||
} | ||
} |
76 changes: 76 additions & 0 deletions
76
Modules/GenHTTP.Modules.I18n/Provider/LocalizationConcern.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
using GenHTTP.Api.Content; | ||
using GenHTTP.Api.Protocol; | ||
using System.Globalization; | ||
|
||
namespace GenHTTP.Modules.I18n.Provider; | ||
|
||
public sealed class LocalizationConcern : IConcern | ||
{ | ||
#region Get-/Setters | ||
|
||
public IHandler Content { get; } | ||
|
||
private readonly CultureInfo _defaultCulture; | ||
private readonly CultureSelectorCombinedAsyncDelegate _cultureSelector; | ||
private readonly CultureFilterAsyncDelegate _cultureFilter; | ||
private readonly AsyncOrSyncSetter[] _cultureSetters; | ||
|
||
#endregion | ||
|
||
#region Initialization | ||
|
||
public LocalizationConcern( | ||
IHandler content, | ||
CultureInfo defaultCulture, | ||
CultureSelectorCombinedAsyncDelegate cultureSelector, | ||
CultureFilterAsyncDelegate cultureFilter, | ||
AsyncOrSyncSetter[] cultureSetters | ||
) | ||
{ | ||
Content = content; | ||
|
||
_defaultCulture = defaultCulture; | ||
_cultureSelector = cultureSelector; | ||
_cultureFilter = cultureFilter; | ||
|
||
_cultureSetters = cultureSetters; | ||
} | ||
|
||
#endregion | ||
|
||
#region Functionality | ||
|
||
public ValueTask PrepareAsync() => Content.PrepareAsync(); | ||
|
||
public async ValueTask<IResponse?> HandleAsync(IRequest request) | ||
{ | ||
var culture = await ResolveCultureInfoAsync(request) ?? _defaultCulture; | ||
|
||
foreach(var _cultureSetter in _cultureSetters) | ||
{ | ||
_cultureSetter.SyncSetter?.Invoke(request, culture); | ||
|
||
if (_cultureSetter.AsyncSetter != null) | ||
{ | ||
await _cultureSetter.AsyncSetter(request, culture); | ||
} | ||
} | ||
|
||
return await Content.HandleAsync(request); | ||
} | ||
|
||
private async ValueTask<CultureInfo?> ResolveCultureInfoAsync(IRequest request) | ||
{ | ||
await foreach (var candidate in _cultureSelector(request)) | ||
{ | ||
if (await _cultureFilter(request, candidate)) | ||
{ | ||
return candidate; | ||
} | ||
} | ||
return null; | ||
} | ||
|
||
#endregion | ||
|
||
} |
Oops, something went wrong.