.hexagon_web.1.2.23.source-code.Web.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hexagon_web Show documentation
Show all versions of hexagon_web Show documentation
The atoms of your platform
package com.hexagonkt.web
import java.util.Locale.forLanguageTag as localeFor
import com.hexagonkt.http.server.Call
import com.hexagonkt.serialization.SerializationManager
import java.nio.charset.Charset.defaultCharset
import java.util.*
import com.hexagonkt.settings.SettingsManager.settings
import com.hexagonkt.templates.TemplateManager.render
import com.hexagonkt.templates.TemplatePort
import kotlinx.html.HTML
import kotlinx.html.html
import kotlinx.html.stream.createHTML
fun Call.templateType(template: String) {
if (response.contentType == null) {
val mimeType = SerializationManager.contentTypeOf(template.substringAfterLast('.'))
response.contentType = "$mimeType; charset=${defaultCharset().name()}"
}
}
fun Call.fullContext(): Map {
val extraParameters = mapOf(
"path" to request.path.removeSuffix("/"), // Do not allow trailing slash
"lang" to obtainLocale().language
)
return settings + session.attributes + extraParameters
}
/**
* TODO Review order precedence and complete code (now only taking request attribute)
*
* 1. Request
* 2. Session
* 3. Cookie
* 4. Accept-language
* 5. Server default locale
*/
fun Call.obtainLocale(): Locale = when {
attributes["lang"] as? String != null -> localeFor(attributes["lang"] as String)
else -> Locale.getDefault()
}
fun Call.template(
templateAdapter: TemplatePort,
templateName: String,
locale: Locale = obtainLocale(),
context: Map = fullContext()
) {
templateType(templateName)
ok(render(templateAdapter, templateName, locale, context))
}
/**
* Return HTML setting the proper content type.
*/
fun Call.html(block: HTML.() -> Unit) {
ok(createHTML().html { block() }, "text/html")
}