emptygif
語言: 繁體中文

所有語言和框架

Spring WebFlux (Kotlin coRouter) Kotlin

適用於 Spring WebFlux (Kotlin coRouter) 的 Kotlin 程式碼片段,以空 GIF 回應對 /pixel.gif 的請求,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 範例