https://kotlinlang.org logo
#ktor
Title
# ktor
m

Marko Kunic

01/11/2022, 4:58 PM
does anyone have an example of how would I load an
.env
variables into ktor before starting local env or running tests?
👍 1
b

Big Chungus

01/11/2022, 5:06 PM
You can't add env variables to a jvm process once it's started, so your only option is to read that file from gradle and append env variables to task's jvm fork
t

Todd

01/11/2022, 6:43 PM
This is what I do for when I run
gradlew run
Copy code
val run by tasks.getting(JavaExec::class) {
    file(".env").readLines().forEach {
        if (it.isNotEmpty() && !it.startsWith("#")) {
            val equalsPos = it.indexOf("=")
            val key = it.substring(0, equalsPos)
            val value = it.substring(equalsPos + 1)

            if (System.getenv(key) == null) {
                environment[key] = value
            }
        }
    }
}
Doesn’t handle all of the cases, but can probably do what you need
n

Nicolas Picon

01/12/2022, 2:27 PM
I use Dotenv for this -> https://github.com/cdimascio/dotenv-java There is a doten-kotlin plugin by the same author, but it doesn’t add much imo
a

Aleksei Tirman [JB]

01/13/2022, 2:39 PM
You can use the HOCON configuration that loads values from environment variables https://ktor.io/docs/configurations.html#environment-variables.
47 Views