在http4s中发送JSON响应的正确方法是什么?

Ale*_*ein 4 scala http4s zio

不久前,我从akka-http切换到http4s。我想要正确执行的基本操作之一-JSON处理,尤其是发送JSON响应。

我决定在ZIO中使用http4s而不是cat,因此这是http路由的样子:

import fs2.Stream
import org.http4s._
import org.http4s.dsl.io._
import org.http4s.implicits._
import scalaz.zio.Task
import scalaz.zio.interop.catz._
import io.circe.generic.auto._
import io.circe.syntax._

class TweetsRoutes {

  case class Tweet(author: String, tweet: String)

  val helloWorldService = HttpRoutes.of[Task] {
    case GET -> Root / "hello" / name => Task {
      Response[Task](Ok)
        .withBodyStream(Stream.emits(
          Tweet(name, "dummy tweet text").asJson.toString.getBytes
        ))
    }
  }.orNotFound

}
Run Code Online (Sandbox Code Playgroud)

如您所见,JSON序列化部分非常冗长:

.withBodyStream(Stream.emits(
  Tweet(name, "dummy tweet text").asJson.toString.getBytes
))
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以在响应中发送JSON吗?

tox*_*unk 6

Yes, there is: define and Encoder and Decoder for Task:

implicit def circeJsonDecoder[A](
      implicit decoder: Decoder[A]
  ): EntityDecoder[Task, A] = jsonOf[Task, A]
  implicit def circeJsonEncoder[A](
      implicit encoder: Encoder[A]
  ): EntityEncoder[Task, A] = jsonEncoderOf[Task, A]
Run Code Online (Sandbox Code Playgroud)

this way there is no need to transform to bytes.

EDIT: there is a full example here: https://github.com/mschuwalow/zio-todo-backend/blob/develop/src/main/scala/com/schuwalow/zio/todo/http/TodoService.scala

HT: @mschuwalow