Environments

note

Environments - 图1

This help topic is in development and will be updated in the future.

You might want to do different things depending on whether your server is running locally or on your production machine.

Ktor doesn’t impose any way for doing this, but here are some guidelines you can use, in case you were wondering about it.

HOCON & ENV

You can use the application.conf file to set a variable that will hold the environment, then check that variable at runtime and decide what to do. You can configure it to check an environment variable KTOR_ENV and to provide a default value dev. Then in production you set the KTOR_ENV=prod.

For example:

application.conf:

  1. ktor {
  2. environment = dev
  3. environment = ${?KTOR_ENV}
  4. }

You can access this config from the application, and use some extension properties to make your life easier:

  1. fun Application.module() {
  2. when {
  3. isDev -> {
  4. // Do things only in dev
  5. }
  6. isProd -> {
  7. // Do things only in prod
  8. }
  9. }
  10. // Do things for all the environments
  11. }
  12. val Application.envKind get() = environment.config.property("ktor.environment").getString()
  13. val Application.isDev get() = envKind == "dev"
  14. val Application.isProd get() = envKind != "dev"