jvmMain.kr.jadekim.jext.ktor.extension.locale.kt Maven / Gradle / Ivy
The newest version!
package kr.jadekim.jext.ktor.extension
import io.ktor.server.application.*
import io.ktor.server.request.*
import java.util.*
fun ApplicationCall.locale(
support: List,
default: Locale = support.first(),
cookieName: String? = "language"
): Locale {
var languages = cookieName?.let { languageFromCookie(it) }
if (languages.isNullOrEmpty()) {
languages = acceptLanguage()
}
if (languages.isEmpty()) {
return default
}
return Locale.lookup(languages, support) ?: default
}
fun ApplicationCall.acceptLanguage(): List {
val text = request.acceptLanguage()
if (text.isNullOrBlank()) {
return emptyList()
}
return try {
Locale.LanguageRange.parse(text)
} catch (e: Exception) {
parseLanguage(text)
}
}
fun ApplicationCall.languageFromCookie(cookieName: String = "language"): List {
val text = request.cookies[cookieName]
if (text.isNullOrBlank()) {
return emptyList()
}
return try {
Locale.LanguageRange.parse(text)
} catch (e: Exception) {
parseLanguage(text)
}
}
private fun parseLanguage(text: String): List = text.split(',').flatMap {
val weightIndex = it.indexOf(';')
val dropIndex = it.indexOf(';', weightIndex + 1)
if (weightIndex < 0 || dropIndex < 0) {
return@flatMap Locale.LanguageRange.parse(it)
}
Locale.LanguageRange.parse(it.substring(0, dropIndex))
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy