web-lang 0.1.0

Match languages with the http `Accept-Language` header.
Documentation
  • Coverage
  • 100%
    5 out of 5 items documented4 out of 5 items with examples
  • Size
  • Source code size: 45.53 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.43 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • Homepage
  • alvra/web-lang
    1 1 1
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • alvra

Web-Lang

Crates.io Documentation License unsafe forbidden

Match a languages from the http Accept-Language header, urls, or other sources.

Language tags (eg: "en-au") are never validated, this crate simply tries to make sense of whatever value it is given, ignoring any input that it cannot understand, and find the best match based on a few simple rules.

This crate is inspired by Django's translation handling.

Features

  • No unsafe code (#[forbid(unsafe_code)])
  • No panics
  • Tested; code coverage: 100% (morally)
  • No dependencies

Example

Simply pass an iterable of language tags and the Accept-Language header to find the best match.

assert_eq!(
    match_accept(
        ["en", "en-au", "de"],
        "de;q=0.5, en-gb;q=0.9, ja;q=0.2, *;q=0.1"
    ),
    Some("en")
);

Complete example with a custom language enum.

use web_lang::{Language, match_accept};

#[derive(Copy, Clone, PartialEq, Debug)]
enum MyLanguage {
    English,
    AustralianEnglish,
    German,
    Japanese,
}

impl Language for MyLanguage {
    fn tag(&self) -> &str {
        match self {
            Self::English => "en",
            Self::AustralianEnglish => "en-au",
            Self::German => "de",
            Self::Japanese => "ja",
        }
    }
}

const LANGUAGES: &[MyLanguage] = &[
    MyLanguage::English,
    MyLanguage::AustralianEnglish,
    MyLanguage::German,
    MyLanguage::Japanese
];

// Use your own language enum.
assert_eq!(
    match_accept(
        LANGUAGES.iter().copied(),
        "de;q=0.5, en-gb;q=0.9, ja;q=0.2, *;q=0.1"
    ),
    Some(MyLanguage::English)
);

Documentation

Documentation

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.