Localization
Runs on your machineResponds in the language preferred by the user.
Greets visitors in their language and writes the date the way they are used to. The language is taken from
the lang query parameter, or else from the Accept-Language header that browsers send; English is the
fallback.
The localization concern sets the culture for every request, so the code simply uses
CultureInfo.CurrentCulture. Supports decides which languages the application offers - here the ones it
has a greeting for, regional variants such as de-CH included.
Runs on your machine only. The server of this website runs without culture data (in globalization-invariant mode), so it cannot switch languages.
To run it, create a console app (dotnet new console), add GenHTTP (dotnet add package GenHTTP.Full), replace Program.cs with the code below and start it with dotnet run - it answers at http://localhost:8080/.
using System.Globalization;
using GenHTTP.Engine.Internal;
using GenHTTP.Modules.Functional;
using GenHTTP.Modules.I18n;
using GenHTTP.Modules.Layouting;
using GenHTTP.Modules.Practices;
var greetings = new Dictionary<string, string>
{
["en"] = "Hello",
["de"] = "Hallo",
["fr"] = "Bonjour"
};
var greeting = Inline.Create()
.Get(() =>
{
var culture = CultureInfo.CurrentCulture;
return $"{greetings[culture.TwoLetterISOLanguageName]}! {DateTime.Now.ToString("D", culture)}";
});
var localization = Localization.Create()
.FromQuery("lang")
.FromHeader()
.Supports(culture => greetings.ContainsKey(culture.TwoLetterISOLanguageName)) // accepts regional variants such as de-CH
.Default(CultureInfo.GetCultureInfo("en"))
.Setter(currentCulture: true, currentUiCulture: true);
var app = Layout.Create()
.Add("greeting", greeting) // GET /greeting/?lang=fr
.Add(localization);
await Host.Create()
.Handler(app)
.Defaults()
.RunAsync();
Try it
With the sample running on your machine:
Prefer Swiss German
curl -i -H "Accept-Language: de-CH, en;q=0.8" http://localhost:8080/greeting/Choose French
curl -i http://localhost:8080/greeting/?lang=frPrefer Japanese
Not supported, falls back to English
curl -i -H "Accept-Language: ja" http://localhost:8080/greeting/