emptygif
言語: 日本語

すべての言語・フレームワーク

Spring WebFlux (Kotlin coRouter) Kotlin

/pixel.gif へのリクエストに空の GIF を返す、Spring WebFlux (Kotlin coRouter) 用の Kotlin スニペット。GIF は起動時に一度だけデコードします。

Spring WebFlux (Kotlin coRouter) Kotlin

インストール
implementation("org.springframework.boot:spring-boot-starter-webflux"); implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
ファイル
PixelApplication.kt
実行
./gradlew bootRun
package com.example.pixel

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.http.CacheControl
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.bodyValueAndAwait
import org.springframework.web.reactive.function.server.coRouter
import java.util.Base64

private val GIF: ByteArray = Base64.getDecoder().decode("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")

@SpringBootApplication
class PixelApplication {
    @Bean
    fun pixelRoutes() = coRouter {
        GET("/pixel.gif") {
            ok().contentType(MediaType.IMAGE_GIF)
                .contentLength(GIF.size.toLong())
                .cacheControl(CacheControl.noStore())
                .bodyValueAndAwait(GIF)
        }
    }
}

fun main(args: Array<String>) {
    runApplication<PixelApplication>(*args)
}

このスニペットは実行し、返されたバイト列を照合しました。

確認

curl -sI http://localhost:8080/pixel.gif

公式サイト: Spring WebFlux (Kotlin coRouter)

Kotlin の他の例