Skip to content

Instantly share code, notes, and snippets.

@mantono
Last active October 28, 2019 20:04
Show Gist options
  • Save mantono/5548f792f9dbc439377a8e653973fc04 to your computer and use it in GitHub Desktop.
Save mantono/5548f792f9dbc439377a8e653973fc04 to your computer and use it in GitHub Desktop.
Configuration loading with Typesafe config in Kotlin
package com.mantono
/**
* implementation("com.typesafe:config:1.4.0")
* See https://github.com/lightbend/config
*/
import com.typesafe.config.ConfigFactory
import com.typesafe.config.Config as TypeSafeConfig
object Config: Map<String, String> by loadProperties()
fun Map<String, String>.forContext(context: String): Map<String, String> =
this.asSequence()
.filter { it.key.startsWith(context) }
.map { it.key.removePrefix("$context.") to it.value }
.toMap()
private fun loadProperties(): Map<String, String> {
val env = Environment()
val config = ConfigFactory.load().forEnvironment(env)
return config.entrySet().asSequence()
.map { it.key to it.value.unwrapped().toString() }
.toMap()
}
private fun TypeSafeConfig.forEnvironment(env: Environment): TypeSafeConfig {
val envKeyPrefix: String = env.name.toLowerCase()
return if(hasPath(envKeyPrefix)) {
this
.getConfig(env.name.toLowerCase())
.withFallback(this)
} else {
this
}
}
/**
* Check if an environment variable is present of if a configuration value is set in application.conf,
* or similar file.
* Config key `jwk.issuer` will become environment variable `JWK_ISSUER`.
* Any environment variable set will take presedence over a value present in a configuration file.
*/
fun getConfig(configKey: String): String {
val envVarKey: String = configKey.toUpperCase().replace(".", "_")
val envVarValue: String? = System.getenv(envVarKey)
val configValue: String? = Config[configKey]
return envVarValue ?: configValue
?: throw IllegalStateException("No value found for environment variable '$envVarValue' or config key '$configKey'")
}
enum class Environment {
PRODUCTION,
DEVELOPMENT,
STAGING,
TEST;
companion object {
operator fun invoke(env: String = System.getenv().getValue("APP_ENV")): Environment {
return when(val appEnv = env.trim().toUpperCase()) {
"TEST" -> TEST
"DEV" -> DEVELOPMENT
"STAGE" -> STAGING
"PROD" -> PRODUCTION
else -> valueOf(appEnv)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment