http4s Scala
適用於 http4s 的 Scala 程式碼片段,以空 GIF 回應對 /pixel.gif 的請求,GIF 在啟動時只解碼一次。
http4s Scala
import cats.effect.{IO, IOApp}
import com.comcast.ip4s.*
import org.http4s.*
import org.http4s.dsl.io.*
import org.http4s.ember.server.EmberServerBuilder
import org.http4s.headers.{`Cache-Control`, `Content-Type`}
object Main extends IOApp.Simple:
private val gif = java.util.Base64.getDecoder.decode("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
private val PixelPath = Uri.Path.unsafeFromString("/pixel.gif")
private val routes = HttpRoutes.of[IO] { case GET -> PixelPath =>
Ok(gif, `Content-Type`(MediaType.image.gif), `Cache-Control`(CacheDirective.`no-store`))
}
val run = EmberServerBuilder
.default[IO]
.withHost(ipv4"0.0.0.0")
.withPort(port"8080")
.withHttpApp(routes.orNotFound)
.build
.useForever
我們執行了這段程式碼,並比對了它回傳的位元組。
驗證
curl -sI http://localhost:8080/pixel.gif