### Install and Use AutoHeadResponse Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-auto-head-response/README.md Install the AutoHeadResponse plugin to enable automatic HEAD request handling. This example shows how to install the plugin and define a GET route that will also respond to HEAD requests. ```kotlin install(AutoHeadResponse) routing { get("/home") { call.respondText("This is a response to a GET, but HEAD also works") } } ``` -------------------------------- ### Serve AsyncAPI Documentation with Ktor Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/com.asyncapi/server-asyncapi/README.md Install the AsyncApiPlugin and configure an AsyncApiExtension to serve AsyncAPI documentation. This example demonstrates setting up basic info and servers for the API. ```kotlin fun main() { embeddedServer(Netty, port = 8000) { install(AsyncApiPlugin) { extension = AsyncApiExtension.builder(order = 10) { info { title("Gitter Streaming API") version("1.0.0") } servers { // ... } // ... } } }.start(wait = true) } @Channel( value = "/rooms/{roomId}", parameters = [ Parameter( value = "roomId", schema = Schema( type = "string", examples = ["53307860c3599d1de448e19d"] ) ) ] ) class RoomsChannel { @Subscribe(message = Message(ChatMessage::class)) fun publish(/*...*/): Unit { /*...*/ } } @Message data class ChatMessage( val id: String, val text: String ) ``` -------------------------------- ### Enable Gzip and Deflate Compression Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-compression/README.md Installs the Compression plugin and enables both gzip and deflate encoders. This is a basic setup for general compression. ```kotlin install(Compression) { gzip() deflate() } ``` -------------------------------- ### HttpCache with Logging Example Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-caching/README.md Demonstrates installing HttpCache alongside the Logging plugin and making two identical requests. The second request should be served from the cache if the resource's Cache-Control headers permit. ```kotlin val client = HttpClient(CIO) { install(HttpCache) install(Logging) { level = LogLevel.INFO } } client.get("http://localhost:8080/customer/1") client.get("http://localhost:8080/customer/1") } ``` -------------------------------- ### Install and Configure FreeMarker Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-freemarker/README.md Install the FreeMarker plugin and configure it to load templates from the classpath. This setup is necessary for using FreeMarker views in your Ktor application. ```kotlin install(FreeMarker) { templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates") } ``` -------------------------------- ### Install Resources Plugin in Ktor Client Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-resources/README.md Installs the Resources plugin by passing it to the `install` function within a client configuration block. Ensure necessary imports are included. ```kotlin import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.resources.* //... val client = HttpClient(CIO) { install(Resources) } ``` -------------------------------- ### Install ContentNegotiation with Jackson Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-jackson/README.md Install the ContentNegotiation plugin and register the Jackson serializer by calling the `jackson` method within the `install` block. ```kotlin install(ContentNegotiation) { jackson() } ``` -------------------------------- ### Install and Use SSE Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-sse/README.md Installs the SSE plugin into the Ktor client and demonstrates receiving an incoming event. ```kotlin val client = HttpClient { install(SSE) } client.sse { val event = incoming.receive() } ``` -------------------------------- ### Install RabbitMQ Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.damirdenis-tudor/server-rabbitmq/README.md Install the RabbitMQ plugin and configure connection details like URI, connection attempts, and delay. ```kotlin install(RabbitMQ) { uri = "amqp://:@
:" defaultConnectionName = "" connectionAttempts = 20 attemptDelay = 10 dispatcherThreadPollSize = 4 tlsEnabled = false } ``` -------------------------------- ### Install ContentNegotiation Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-serialization-json-gson/README.md Installs the ContentNegotiation plugin into the Ktor client. This is a prerequisite for using any serializers. ```kotlin val client = HttpClient(CIO) { install(ContentNegotiation) } ``` -------------------------------- ### Install and Configure Kafka Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.flaxoos/server-kafka/README.md Use the `install(Kafka)` block to configure common, admin, producer, and consumer settings, including SSL/SASL and custom properties. Override common configurations at the client level. ```kotlin install(Kafka) { schemaRegistryUrl = listOf("my.schemaRegistryUrl") common { // <-- Define common configs // properties } admin { // <-- Creates an admin client // properties } producer { // <-- Creates a producer // properties } consumer { clientId = "my-client-id-override" // <-- Override common SOME_CUSTOM_PROPERTY("some-value") // <-- Pass custom property } // Configure SSL/SASL commonSsl { broker { protocol = "TLSv1.2" endpointIdentificationAlgorithm = "" trustStore { location = "path/to/truststore.jks" password = PASSWORD } keyStore { location = "path/to/keystore.jks" password = PASSWORD } keyPassword = PASSWORD } schemaRegistry { // ... } } adminSsl { protocol = "SSL" trustStore { //... } } adminSasl{ jaasConfig = "..." } // ... } ``` -------------------------------- ### Install HttpCache Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-caching/README.md Installs the HttpCache plugin into your Ktor client. This is the basic setup required to enable caching functionality. ```kotlin import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.cache.* //... val client = HttpClient(CIO) { install(HttpCache) } ``` -------------------------------- ### Install and Configure SimpleCache Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/com.ucasoft/server-simple-cache/README.md Install the SimpleCache plugin and configure the cache provider with a specific invalidation time. ```kotlin install(SimpleCache) { cacheProvider { invalidateAt = 10.seconds } } ``` -------------------------------- ### Install KHealth Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/dev.hayden/server-khealth/README.md Basic installation of the KHealth plugin to enable default /ready and /health endpoints. ```kotlin import dev.hayden.KHealth fun main(args: Array) { embeddedServer(Netty, 80) { install(KHealth) }.start(wait = true) } ``` -------------------------------- ### Configure Status Pages Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the StatusPages plugin to map exceptions to custom responses. This example handles any Throwable with a 500 Internal Server Error response. ```kotlin package kastle import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* fun Application.configureStatusPages() { install(StatusPages) { exception { call, cause -> call.respondText( text = "500: $cause", status = HttpStatusCode.InternalServerError ) } } } ``` -------------------------------- ### Install CallLogging with Request Filtering Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-call-logging/README.md Installs the CallLogging plugin and configures it to only log requests that start with '/api/v1'. ```kotlin install(CallLogging) { filter { call -> call.request.path().startsWith("/api/v1") } } ``` -------------------------------- ### Install Basic Cohort Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/com.sksamuel.cohort/server-cohort/README.md Install the Cohort plugin with a basic healthcheck endpoint for Kubernetes. ```kotlin install(Cohort) { // enable healthchecks for kubernetes healthcheck("/health", health) } ``` -------------------------------- ### Install and Configure Mustache Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-mustache/README.md Install the Mustache plugin and configure the MustacheFactory to locate templates in the specified directory. ```kotlin install(Mustache) { mustacheFactory = DefaultMustacheFactory("templates") } ``` -------------------------------- ### Install Koin Plugin in Ktor Application Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.insert-koin/server-koin/README.md Install the Koin plugin by calling `install(Koin)` within your Ktor application's main function. Configure it with logging and modules. ```kotlin fun Application.main() { // Install Koin install(Koin) { slf4jLogger() modules(helloAppModule) } } ``` -------------------------------- ### Install Resources Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-resources/README.md Install the Resources plugin to enable type-safe routing capabilities in your Ktor server. ```kotlin install(Resources) ``` -------------------------------- ### Install DefaultRequest Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-default-request/README.md Installs the DefaultRequest plugin into the HttpClient. This is a common way to enable default request configurations. ```kotlin import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* //... val client = HttpClient(CIO) { install(DefaultRequest) } ``` -------------------------------- ### Install SSE Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-sse/README.md Install the SSE plugin within your Application.module(). ```kotlin install(SSE) ``` -------------------------------- ### Install ForwardedHeaders Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-forwarded-header-support/README.md Install the ForwardedHeaders plugin to enable handling of standard `Forwarded` headers. This is typically done during application setup. ```kotlin install(ForwardedHeaders) ``` -------------------------------- ### Install Kafka Plugin with File Configuration Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.flaxoos/server-kafka/README.md Install the Kafka plugin using `FileConfig.Kafka` to load configurations from an application file. You can specify a custom configuration path if needed. ```kotlin install(FileConfig.Kafka) { // consumerConfig and registerSchemas are still done here } ``` ```kotlin install(FileConfig.Kafka("ktor.my.kafka")) { // consumerConfig and registerSchemas are still done here } ``` -------------------------------- ### Install Bearer Authentication Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-auth-bearer/README.md Call the `bearer` function inside the `install` block to set up bearer authentication for the client. This is the initial step for enabling this feature. ```kotlin import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.auth.* //... val client = HttpClient(CIO) { install(Auth) { bearer { // Configure bearer authentication } } } ``` -------------------------------- ### Install and Configure RateLimiting Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.flaxoos/server-rate-limiting/README.md Apply the RateLimiting plugin within your Ktor routing setup. Configure rate limiter type, rate, capacity, and blacklist/whitelist rules. Customize the response for blacklisted callers. ```kotlin routing { route("limited-route") { install(RateLimiting) { rateLimiter { type = TokenBucket::class rate = 1.seconds capacity = 100 } whiteListedHosts = setOf("trusted-host.com") blackListedAgents = setOf("malicious-agent") blackListedCallerCallHandler = { call -> call.respond(HttpStatusCode.Forbidden, "You are blacklisted and cannot access the API.") } } get { call.respondText("Welcome to our limited route!") } } route("unlimited-route") { get { call.respondText("Welcome to our unlimited route!") } } } ``` -------------------------------- ### Install ContentNegotiation with Gson Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-gson/README.md Install the ContentNegotiation plugin and register the Gson serializer by calling the `gson()` method. This is a prerequisite for JSON serialization/deserialization. ```kotlin install(ContentNegotiation) { gson() } ``` -------------------------------- ### Configure Koog Plugin Programmatically Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/server-koog/README.md Install and configure the Koog plugin within your Ktor application module. This example shows how to set up multiple LLM providers and define a chat route. ```kotlin fun Application.module() { install(Koog) { llm { openAI(apiKey = "your-openai-api-key") anthropic(apiKey = "your-anthropic-api-key") ollama { baseUrl = "http://localhost:11434" } google(apiKey = "your-google-api-key") openRouter(apiKey = "your-openrouter-api-key") deepSeek(apiKey = "your-deepseek-api-key") } } routing { route("/ai") { post("/chat") { val userInput = call.receive() val output = aiAgent(userInput) call.respond(HttpStatusCode.OK, output) } } } } ``` -------------------------------- ### Direct Library Call Example Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.damirdenis-tudor/server-rabbitmq/README.md Interact directly with the RabbitMQ Java library using `libChannel`. Demonstrates publishing a message and setting up a basic consumer. ```kotlin rabbitmq { libChannel(id = 2) { basicPublish("demo-queue", "demo-routing-key", null, "Hello!".toByteArray()) val consumer = object : DefaultConsumer(channel) { override fun handleDelivery( consumerTag: String?, envelope: Envelope?, properties: AMQP.BasicProperties?, body: ByteArray? ) { } } basicConsume("demo-queue", true, consumer) } } ``` -------------------------------- ### Configure Basic Authentication Provider Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-auth-basic/README.md Install the Auth plugin and configure the basic authentication provider with username and password credentials. Set the realm for authentication. ```kotlin val client = HttpClient(CIO) { install(Auth) { basic { credentials { BasicAuthCredentials(username = "jetbrains", password = "foobar") } realm = "Access to the '/' path" } } } ``` -------------------------------- ### Configure Compression Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the Compression plugin to enable transparent gzip/deflate compression for outgoing responses. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.plugins.compression.* fun Application.configureCompression() { install(Compression) } ``` -------------------------------- ### Install MicrometerMetrics with Prometheus Registry Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-metrics-micrometer/README.md Installs the MicrometerMetrics plugin and assigns a Prometheus registry. Ensure PrometheusMeterRegistry and PrometheusConfig are imported. ```kotlin fun Application.module() { val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) install(MicrometerMetrics) { registry = appMicrometerRegistry } } ``` -------------------------------- ### Initialize HttpClient Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Creates a basic `HttpClient` instance. The `_slots("clientConfig")` call ensures that installed client plugins are automatically composed into the client configuration. Requires `io.ktor/client-core`. ```kotlin package kastle import io.ktor.client.HttpClient val httpClient = HttpClient { _slots("clientConfig") // composed by selected client plugins } ``` -------------------------------- ### Install User-Agent Plugin with Browser Agent Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-user-agent/README.md Install the UserAgent plugin using the BrowserUserAgent function to set a browser-like User-Agent header. This can be helpful for compatibility with web servers. ```kotlin val client = HttpClient(CIO) { BrowserUserAgent() // ... or CurlUserAgent() } ``` -------------------------------- ### Install User-Agent Plugin with Custom Agent Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-user-agent/README.md Install the UserAgent plugin and set a custom User-Agent string. This is useful for identifying your client application. ```kotlin import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* // ... val client = HttpClient(CIO) { install(UserAgent) { agent = "Ktor client" } } ``` -------------------------------- ### Configure Ktor Client for RPC Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/kotlinx-rpc/README.md Set up the Ktor client to connect to the RPC service. Install the RPC client plugin and configure the service URL and serialization. ```kotlin val rpcClient = HttpClient { installRPC() }.rpc { url("ws://localhost:8080/awesome") rpcConfig { serialization { json() } } } val service = rpcClient.withService() service.greeting("Alex") service.getNews("KotlinBurg").collect { article -> println(article) } ``` -------------------------------- ### Install Basic Retry Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-retry/README.md Installs the HttpRequestRetry plugin with default settings. Use this for basic retry functionality without custom conditions. ```kotlin import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* //... val client = HttpClient(CIO) { install(HttpRequestRetry) } ``` -------------------------------- ### Install WebSockets Feature Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-websockets/README.md Installs the basic WebSockets feature into your Ktor application. No specific configuration is provided. ```kotlin install(WebSockets) ``` -------------------------------- ### Install DefaultHeaders Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-default-headers/README.md Installs the DefaultHeaders plugin to add standard Server and Date headers to responses. Further configuration for custom headers or overriding the Server header is detailed in the official documentation. ```kotlin install(DefaultHeaders) ``` -------------------------------- ### Install ContentNegotiation with JSON serializer Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-content-negotiation/README.md Install the ContentNegotiation plugin and register the JSON serializer by calling the json() method. This enables deserialization of incoming JSON data. ```kotlin install(ContentNegotiation) { json() } ``` -------------------------------- ### Run Ktor Server with CIO Engine Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-cio/README.md Reference the CIO engine from your own main function to start an embedded Ktor server. Ensure necessary imports are included. ```kotlin import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.engine.* import io.ktor.server.cio.* fun main(args: Array) { embeddedServer(CIO, port = 8080) { routing { get("/") { call.respondText("Hello, world!") } } }.start(wait = true) } ``` -------------------------------- ### Install Sessions Plugin with Cookie Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-sessions/README.md Install the Sessions plugin and configure it to use cookies for session management. Specify the session data class and a cookie name. ```kotlin install(Sessions) { cookie("user_session") } ``` -------------------------------- ### Configure Ktor Server with RPC Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/kotlinx-rpc/README.md Integrate kotlinx.rpc into your Ktor server. Install the RPC plugin and register your service implementation within the routing configuration. ```kotlin fun main() { embeddedServer(Netty, 8080) { install(RPC) routing { rpc("/awesome") { rpcConfig { serialization { json() } } registerService { AwesomeServiceImpl() } } } }.start(wait = true) } ``` -------------------------------- ### Install HttpCallValidator Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-response-validation/README.md Install the `HttpCallValidator` plugin within the client configuration block to enable custom response validation. ```kotlin val client = HttpClient(CIO) { HttpResponseValidator { // ... } } ``` -------------------------------- ### Configure WebJars Serving Path and Time Zone Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-webjars/README.md Install the Webjars plugin and configure the path for serving assets and the time zone for caching headers. Ensure ConditionalHeaders plugin is installed for caching support. ```kotlin install(Webjars) { path = "assets" zone = ZoneId.of("EST") } ``` -------------------------------- ### Configure Micrometer Metrics Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the MicrometerMetrics plugin with a Prometheus registry and sets up a /metrics-micrometer endpoint to expose metrics. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.metrics.micrometer.* import io.ktor.server.response.respond import io.ktor.server.routing.* import io.micrometer.prometheusmetrics.PrometheusConfig import io.micrometer.prometheusmetrics.PrometheusMeterRegistry fun Application.configureMetricsMicrometer() { val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) install(MicrometerMetrics) { registry = appMicrometerRegistry } routing { get("/metrics-micrometer") { call.respond(appMicrometerRegistry.scrape()) } } } ``` -------------------------------- ### Enable Deflate and Gzip Compression on Client Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-content-encoding/README.md Install the ContentEncoding plugin and enable deflate and gzip compression with specified quality values. This configures the client to send the Accept-Encoding header and handle compressed responses. ```kotlin val client = HttpClient(CIO) { install(ContentEncoding) { deflate(1.0F) gzip(0.9F) } } ``` -------------------------------- ### Specify Dependency Parameters in Configuration Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-di/README.md When loading modules from configuration, you can specify the correct parameters for dependencies. This example shows a function signature that accepts a Database dependency. ```kotlin fun Application.endpoints(database: Database) { // etc. } ``` -------------------------------- ### Install HSTS Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-hsts/README.md Installs the HSTS plugin to automatically add Strict Transport Security headers to responses. No configuration is needed for default behavior. ```kotlin install(HSTS) ``` -------------------------------- ### Configure Sessions with Cookie Container Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the Sessions plugin with a cookie-backed session container and sets the SameSite policy to 'lax'. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.sessions.* data class MySession(val count: Int = 0) fun Application.configureSessions() { install(Sessions) { cookie("MY_SESSION") { cookie.extensions["SameSite"] = "lax" } } } ``` -------------------------------- ### Configure WebSockets Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the WebSockets plugin with custom configurations for ping period, timeout, max frame size, and masking. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.websocket.* import kotlin.time.Duration.Companion.seconds fun Application.configureWebsockets() { install(WebSockets) { pingPeriod = 15.seconds timeout = 15.seconds maxFrameSize = Long.MAX_VALUE masking = false } } ``` -------------------------------- ### Example Authorization Header Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-auth-bearer/README.md Demonstrates the format of the `Authorization` header when using Bearer tokens. The access token is prefixed with 'Bearer '. ```http GET http://localhost:8080/ Authorization: Bearer abc123 ``` -------------------------------- ### Configure Pebble Template Loading Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-pebble/README.md Install the Pebble plugin and configure it to load templates from the classpath. Specify a prefix to locate templates within a specific directory. ```kotlin install(Pebble) { loader(ClasspathLoader().apply { prefix = "templates" }) } ``` -------------------------------- ### Configure HttpsRedirect Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-https-redirect/README.md Install the HttpsRedirect plugin and configure the SSL port and redirect type. Use `permanentRedirect = true` for a 301 redirect, or `false` for a 302 redirect. ```kotlin install(HttpsRedirect) { sslPort = 443 permanentRedirect = true } ``` -------------------------------- ### Ktor Plugin Registry YAML Configuration Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Example YAML configuration for the Ktor plugin registry, specifying platform and dependencies. ```yaml platform: jvm dependencies: - $ktorLibs.server.auth.jwt sources: - target: slot://io.ktor/server-core/applicationYaml text: |- jwt: domain: "https://jwt-provider-domain/" audience: "jwt-audience" realm: "ktor sample app" ``` -------------------------------- ### Configure Content Negotiation with kotlinx.serialization Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the ContentNegotiation plugin and configures it to use kotlinx.serialization JSON support. The specific serializer is expected to be provided by another slot. ```kotlin // repository/io.ktor/server-content-negotiation/server/src/ContentNegotiation.kt package kastle import io.ktor.server.application.* import io.ktor.server.plugins.contentnegotiation.ContentNegotiation fun Application.configureSerialization() { install(ContentNegotiation) { _slot("serializationConfig") // filled by the selected serializer } } ``` -------------------------------- ### Declare Database Dependency via Module Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-di/README.md Provide a Database implementation using the dependencies DSL within your modules. This example shows how to provide a PostgresDatabase instance, resolving its configuration through the property function. ```kotlin fun Application.database() { dependencies { provide { PostgresDatabase(property()) } } } ``` -------------------------------- ### Configure Request Validation Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the RequestValidation plugin to validate incoming request bodies. This example validates String bodies to ensure they start with 'Hello'. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.plugins.requestvalidation.RequestValidation import io.ktor.server.plugins.requestvalidation.ValidationResult fun Application.configureRequestValidation() { install(RequestValidation) { validate { bodyText -> if (!bodyText.startsWith("Hello")) ValidationResult.Invalid("Body text should start with 'Hello'") else ValidationResult.Valid } } } ``` -------------------------------- ### Install Firebase Authentication Provider Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/com.kborowy/server-firebase-auth-provider/README.md Install the Firebase authentication provider within your Ktor application. Configure the realm and a validation lambda to process Firebase tokens and return user principals. ```kotlin install(Authentication) { firebase("my-auth") { realm = "My Server" setup { // required, see configuration below } validate { token -> UserIdPrincipal(token.uid) } } } ``` -------------------------------- ### Serve OpenAPI Documentation Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-openapi/README.md Call the `openAPI` method within your routing block to create a GET endpoint for your OpenAPI documentation. Specify the path for the endpoint and the location of your OpenAPI specification file. ```kotlin import io.ktor.server.plugins.openapi.* fun Application.main() { routing { openAPI(path="openapi", swaggerFile = "openapi/documentation.yaml") } } ``` -------------------------------- ### Build the Project Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/CONTRIBUTING.md Run this command to build the project and execute tests, ensuring plugin artifacts can be resolved and the registry builder functions correctly. ```bash ./gradlew build ``` -------------------------------- ### Configure WebSockets Options Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-websockets/README.md Installs and configures the WebSockets feature with custom options for ping period, timeout, maximum frame size, and masking. ```kotlin install(WebSockets) { pingPeriod = 15.seconds timeout = 15.seconds maxFrameSize = Long.MAX_VALUE masking = false } ``` -------------------------------- ### Configure and Use Memory Cache Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/com.ucasoft/server-simple-memory-cache/README.md Install the SimpleCache plugin with memory caching configured. Use the `cacheOutput` function to cache responses for specific routes with defined or default invalidation periods. ```kotlin install(SimpleCache) { memoryCache { invalidateAt = 10.seconds } } routing { cacheOutput(2.seconds) { get("short-cache") { call.respond(Random.nextInt().toString()) } } cacheOutput { get("default-cache") { call.respond(Random.nextInt().toString()) } } } ``` -------------------------------- ### Configure Server-Sent Events Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the SSE plugin to enable server-sent event streams on any route. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.sse.* fun Application.configureSse() { install(SSE) } ``` -------------------------------- ### Run Jaeger Docker Container Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.opentelemetry.instrumentation/server-open-telemetry/README.md Start a Jaeger all-in-one Docker container for tracing. Jaeger UI will be available on http://localhost:16686/search. ```bash docker run -d --name jaeger_instance \ -p 4317:4317 \ -p 16686:16686 \ jaegertracing/all-in-one:latest ``` -------------------------------- ### Digest Authentication Flow Example Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-auth-digest/README.md Illustrates the typical WWW-Authenticate header sent by the server in a Digest authentication challenge. ```http WWW-Authenticate: Digest realm="Access to the '/' path", nonce="e4549c0548886bc2", algorithm="MD5" ``` -------------------------------- ### Configure Ktor Server with OpenTelemetry Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.opentelemetry.instrumentation/server-open-telemetry/README.md Integrate OpenTelemetry into your Ktor application by installing the KtorServerTelemetry plugin. Ensure OpenTelemetry is initialized with a service name. ```kotlin val openTelemetry: OpenTelemetry = getOpenTelemetry(serviceName = "your-service-name") embeddedServer(Netty, 8080) { install(KtorServerTelemetry) { setOpenTelemetry(openTelemetry) } }.start(wait = true) ``` -------------------------------- ### Custom Agent Strategies with Koog Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/server-koog/README.md Utilize custom agent strategies for specialized AI interactions. This example demonstrates using the 'reActStrategy' for agent execution. ```kotlin post("/custom-agent") { val userInput = call.receive() val output = aiAgent(reActStrategy(), userInput) call.respond(HttpStatusCode.OK, output) } ``` -------------------------------- ### Configure CORS Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the CORS plugin, allowing specific HTTP methods, headers, and any host. Restrict hosts in production. ```kotlin package kastle import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.cors.routing.* fun Application.configureCors() { install(CORS) { allowMethod(HttpMethod.Options) allowMethod(HttpMethod.Put) allowMethod(HttpMethod.Delete) allowMethod(HttpMethod.Patch) allowHeader(HttpHeaders.Authorization) allowHeader("MyCustomHeader") anyHost() // Restrict in production } } ``` -------------------------------- ### Get Cookies for a URL Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-cookies/README.md Retrieve all cookies associated with a specific URL using the `cookies` function. This function is available after installing the HttpCookies plugin. ```kotlin client.cookies("http://0.0.0.0:8080/") ``` -------------------------------- ### Configure Client Request Retry Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs `HttpRequestRetry` on the client, configuring it to retry up to 5 times on server errors with exponential backoff. Requires `io.ktor/client-retry`. ```kotlin package kastle import io.ktor.client.* import io.ktor.client.plugins.* fun HttpClientConfig<*>.configureClientRetry() { install(HttpRequestRetry) { retryOnServerErrors(maxRetries = 5) exponentialDelay() } } ``` -------------------------------- ### Build the Plugin Registry Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/CONTRIBUTING.md Run this command to compile and export the plugin metadata. This is used for validation and for exporting to consumer applications like start.ktor.io. ```bash ./gradlew buildRegistry ``` -------------------------------- ### Configure SLF4J Reporter for Metrics Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-metrics/README.md Installs the DropwizardMetrics plugin and configures an SLF4J reporter to emit metrics every 10 seconds. Ensure the SLF4J logging is set up to capture the output. ```kotlin install(DropwizardMetrics) { Slf4jReporter.forRegistry(registry) .outputTo(log) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build() .start(10, TimeUnit.SECONDS) } ``` -------------------------------- ### Configure Client Bearer Authentication Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the `Auth` plugin on the HTTP client with Bearer token support. Provides callbacks for `loadTokens` and optionally `refreshTokens`. Requires `io.ktor/client-auth-bearer`. ```kotlin package kastle import io.ktor.client.* import io.ktor.client.plugins.auth.* import io.ktor.client.plugins.auth.providers.* fun HttpClientConfig<*>.configureClientAuthBearer() { install(Auth) { bearer { loadTokens { BearerTokens( accessToken = "abc123", refreshToken = "xyz111" ) } // refreshTokens { /* call token refresh endpoint */ } } } } ``` -------------------------------- ### Connect and Call gRPC Service from Client Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/plugins/server/org.jetbrains/kotlinx-rpc-grpc/3.0/documentation.md Use `GrpcClient` to establish a connection to the gRPC server and invoke service methods. Configure credentials as needed. ```kotlin import com.example.proto.ClientGreeting import com.example.proto.SampleService import com.example.proto.invoke val client = GrpcClient("localhost", GRPC_PORT) { credentials = plaintext() } val service = client.withService() val response = service.greeting(ClientGreeting { name = "World" }) println("Response: ${response.content}") client.shutdown() client.awaitTermination() ``` -------------------------------- ### Install HttpCookies Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-cookies/README.md Install the HttpCookies plugin in the Ktor client configuration. This enables automatic cookie handling between requests. ```kotlin val client = HttpClient(CIO) { install(HttpCookies) } ``` -------------------------------- ### Serve Files from a Folder with Ktor Static Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-static-content/README.md Use the `static` block with the `files` function to serve content from a directory. The URL path is relative to the application path. ```kotlin routing { static("assets") { files("css") } } ``` -------------------------------- ### Configure Dependency Injection Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Sets up Ktor's built-in DI system by registering providers in the `dependencies {}` block. Injected services are resolved automatically by type in routes and plugins. Requires `io.ktor/server-di`. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.plugins.di.* fun interface GreetingService { fun greet(): String } fun Application.configureDependencyInjection() { dependencies { provide { GreetingService { "Hello, World!" } } } } ``` -------------------------------- ### Connect to MongoDB Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/server-mongodb/README.md Establishes a connection to the MongoDB database using a provided URI. Ensure the MongoDB server is running and accessible. ```kotlin val uri = "mongodb://127.0.0.1:27017/?maxPoolSize=20&w=majority" val mongoClient = MongoClients.create(uri) val database = mongoClient.getDatabase(databaseName) ``` -------------------------------- ### Run Kotest Suite for Plugin Testing Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/README.md Execute the Kotest suite to verify that all plugins in the registry result in a successfully built project with passing tests. ```bash ./gradlew :test:kotest ``` -------------------------------- ### Install LineSignatureVerification Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.cotrin8672/server-line-webhook/README.md Install the LineSignatureVerification plugin on the webhook endpoint. Ensure the CHANNEL_SECRET environment variable is set with your LINE channel secret for verification. ```kotlin route("/callback") { install(DoubleReceive) install(LineSignatureVerification) { channelSecret = System.getenv("CHANNEL_SECRET") } post { call.respond(HttpStatusCode.OK) } } ``` -------------------------------- ### Configure Basic Authentication Provider Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-auth-basic/README.md Set up a Basic authentication provider with a realm and a validation function. The validation function checks the provided username and password. ```kotlin install(Authentication) { basic("auth-basic") { realm = "Access to the '/' path" validate { credentials -> if (credentials.name == "jetbrains" && credentials.password == "foobar") { UserIdPrincipal(credentials.name) } else { null } } } } ``` -------------------------------- ### Digest Authentication Request Example Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-auth-digest/README.md Shows the Authorization header format with credentials for a Digest authenticated request. ```http Authorization: Digest username="jetbrains", realm="Access to the '/' path", nonce="e4549c0548886bc2", uri="/", algorithm=MD5, response="6299988bb4f05c0d8ad44295873858cf" ``` -------------------------------- ### Create and Get Collection Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/server-mongodb/README.md Creates a new collection in the database if it does not exist and then retrieves a reference to it. Collections store related documents. ```kotlin database.createCollection("users") val collection = database.getCollection("users") ``` -------------------------------- ### Configure OpenAPI Route Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Registers an `openAPI` route to serve OpenAPI documentation. This can be from a static file or dynamically generated when the Ktor Gradle plugin's `openApi` feature is enabled. Requires `io.ktor/server-openapi`. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.plugins.openapi.* import io.ktor.server.routing.* fun Application.configureOpenapi() { routing { openAPI(path = "openapi") { // Use a static file: // swaggerFile = "openapi/documentation.yaml" // Or rely on auto-generation via Ktor Gradle plugin } } } ``` -------------------------------- ### Configure CORS Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-cors/README.md Install and configure the CORS plugin to allow cross-origin requests. Specify allowed hosts and headers like ContentType. ```kotlin install(CORS) { allowHost("0.0.0.0:5000") allowHeader(HttpHeaders.ContentType) } ``` -------------------------------- ### Configure Digest Authentication Provider in Ktor Client Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-auth-digest/README.md Configures the Digest authentication provider with credentials and realm. Ensure the Auth plugin is installed. ```kotlin val client = HttpClient(CIO) { install(Auth) { digest { credentials { DigestAuthCredentials(username = "jetbrains", password = "foobar") } realm = "Access to the '/' path" } } } ``` -------------------------------- ### Configure SSE Endpoint in Routing Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-sse/README.md Configure a GET endpoint using the sse function within your routing block to stream Server-Sent Events. ```kotlin install(Routing) { // creates GET endpoint /hello with single // event streamed with content "world" sse("/hello") { send(ServerSentEvent("world")) } } ``` -------------------------------- ### Connect to a Database with Exposed Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/server-exposed/README.md Establish a connection to a database using Exposed's `Database.connect` function. Specify the JDBC connection string, driver class, and authentication credentials. ```kotlin Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "root", password = "") ``` -------------------------------- ### Configure iOS Application Product Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/org.jetbrains/amper/README.md This configuration snippet for `module.yaml` specifies that the product should be an iOS application. ```yaml product: ios/app ``` -------------------------------- ### Configure Caching Headers Plugin Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Installs the CachingHeaders plugin to set Cache-Control directives. It configures specific caching options for CSS content types. ```kotlin package kastle import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.plugins.cachingheaders.* fun Application.configureCachingHeaders() { install(CachingHeaders) { options { call, outgoingContent -> when (outgoingContent.contentType?.withoutParameters()) { ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 24 * 60 * 60)) else -> null } } } } ``` -------------------------------- ### Configure Dependencies via application.yaml Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-di/README.md Add classpath items to the ktor.application.dependencies list in application.yaml to automatically instantiate and provide them. Class names or function references can be used, with parameters resolved automatically. ```yaml # application.yaml ktor: application: dependencies: - com.example.db.PostgresDatabase - com.example.DatabaseKt#configureDb ``` -------------------------------- ### Configure Digest Authentication Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/server-auth-digest/README.md Installs the Digest authentication feature and configures the realm and user provider. The digestProvider fetches the HA1 hash for a given username. ```kotlin install(Authentication) { digest("auth-digest") { realm = "Access to the '/' path" digestProvider { userName, realm -> userTable[userName] } } } ``` -------------------------------- ### Configure Swagger UI Route Source: https://context7.com/ktorio/ktor-plugin-registry/llms.txt Serves the Swagger UI at a configurable path, pointing to an OpenAPI specification. Requires `io.ktor/server-swagger`. ```kotlin package kastle import io.ktor.server.application.* import io.ktor.server.plugins.swagger.* import io.ktor.server.routing.* fun Application.configureSwagger() { routing { swaggerUI(path = "openapi") { // swaggerFile = "openapi/documentation.yaml" } } } ``` -------------------------------- ### Configure Global Request Timeout Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-timeout/README.md Set a global request timeout for all HTTP calls by configuring `requestTimeoutMillis` within the `HttpTimeout` plugin during client installation. ```kotlin val client = HttpClient(CIO) { install(HttpTimeout) { requestTimeoutMillis = 1000 } } ``` -------------------------------- ### Configure Comprehensive Cohort Plugin Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/com.sksamuel.cohort/server-cohort/README.md Enable all features and configure various endpoints for the Cohort plugin, including OS info, JVM details, logging, data sources, system properties, heap/thread dumps, and detailed health check responses. ```kotlin install(Cohort) { // enable an endpoint to display operating system name and version operatingSystem = true // enable runtime JVM information such as vm options and vendor name jvmInfo = true // configure the Logback log manager to show effective log levels and allow runtime adjustment logManager = LogbackManager // show connection pool information dataSources = listOf(HikariDataSourceManager(ds)) // show current system properties sysprops = true // enable an endpoint to dump the heap in hprof format heapDump = true // enable an endpoint to dump threads threadDump = true // set to true to return the detailed status of the healthcheck response verboseHealthCheckResponse = true // enable healthchecks for kubernetes // each of these is optional and can map to any healthcheck url you wish // for example if you just want a single health endpoint, you could use /health healthcheck("/liveness", livechecks) healthcheck("/readiness", readychecks) healthcheck("/startup", startupchecks) } ``` -------------------------------- ### Access Kafka Clients from Application Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.flaxoos/server-kafka/README.md Kafka clients (admin, producer, consumer) are available as properties directly on the `application` instance after the Kafka plugin has been installed. ```kotlin val adminClient = application.kafkaAdminClient val producer = application.kafkaProducer val consumer = application.kafkaConsumer ``` -------------------------------- ### Configure CBOR Serialization Settings Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.ktor/client-serialization-cbor/README.md Configures CBOR serialization with custom settings using CborBuilder. This example shows how to ignore unknown keys during deserialization. ```kotlin import io.ktor.client.plugins.contentnegotiation.* import io.ktor.serialization.kotlinx.cbor.* import kotlinx.serialization.cbor.* val client = HttpClient(CIO) { install(ContentNegotiation) { cbor(Cbor { ignoreUnknownKeys = true }) } } ``` -------------------------------- ### Configure MongoDB Task Manager Source: https://github.com/ktorio/ktor-plugin-registry/blob/main/repository/io.github.flaxoos/server-task-scheduling/README.md Set up a MongoDB-based task manager by specifying the database name and providing a MongoDB client instance. This manager is named 'my mongodb manager'. ```kotlin mongoDb("my mongodb manager") { databaseName = "test" client = MongoClient.create("mongodb://host:port") } ```