Skip to content

Commit

Permalink
Remove HttpApp from internal API and examples
Browse files Browse the repository at this point in the history
  • Loading branch information
987Nabil committed Apr 23, 2024
1 parent da6311c commit a6e9282
Show file tree
Hide file tree
Showing 123 changed files with 807 additions and 1,050 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ import zio.http._

object HelloWorld extends ZIOAppDefault {

val app: HttpApp[Any, Response] =
HttpApp(
val app: Routes[Any, Response] =
Routes(
Method.GET / "text" -> handler(Response.text("Hello World!"))
).toHttpApp
)

override val run =
Server.serve(app).provide(Server.default)
Expand Down
4 changes: 2 additions & 2 deletions docs/dsl/body.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import zio._
import zio.http._

object HelloExample extends ZIOAppDefault {
val app: HttpApp[Any, Response] =
HttpApp(
val app: Routes[Any, Response] =
Routes(
Method.GET / "hello" ->
handler { req: Request =>
for {
Expand Down
12 changes: 6 additions & 6 deletions docs/dsl/cookies.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,15 @@ Let's write a simple example to see how it works:
import zio.http._

object ResponseCookieExample extends ZIOAppDefault {
val httpApp = HttpApp(
val routes = Routes(
Method.GET / "cookie" -> handler {
Response.ok.addCookie(
Cookie.Response(name = "user_id", content = "user123", maxAge = Some(5.days))
)
},
)

def run = Server.serve(httpApp).provide(Server.default)
def run = Server.serve(routes).provide(Server.default)
}
```

Expand Down Expand Up @@ -150,7 +150,7 @@ The cookies can be signed with a signature:
```scala mdoc:silent:nest
val cookie = Cookie.Response("key", "hello", maxAge = Some(5.days))
val app =
HttpApp(
Routes(
Method.GET / "cookie" -> handler {
Response.ok.addCookie(cookie.sign("secret"))
}
Expand All @@ -164,7 +164,7 @@ To sign all the cookies in your routes, we can use `signCookies` middleware:
```scala mdoc:silent:nest
import Middleware.signCookies

val app = HttpApp(
val app = Routes(
Method.GET / "cookie" -> handler(Response.ok.addCookie(cookie)),
Method.GET / "secure-cookie" -> handler(Response.ok.addCookie(cookie.copy(isSecure = true)))
)
Expand Down Expand Up @@ -205,7 +205,7 @@ From HTTP requests, a single cookie can be retrieved with `Request#cookie`:

```scala mdoc:compile-only
private val app4 =
HttpApp(
Routes(
Method.GET / "cookie" -> handler { (req: Request) =>
val cookieContent = req.cookie("sessionId").map(_.content)
Response.text(s"cookie content: $cookieContent")
Expand All @@ -219,7 +219,7 @@ In HTTP requests, cookies are stored in the `Header.cookie` header:

```scala mdoc:compile-only
private val app3 =
HttpApp(
Routes(
Method.GET / "cookie" -> handler { (req: Request) =>
Response.text(
req.header(Header.Cookie)
Expand Down
2 changes: 1 addition & 1 deletion docs/dsl/endpoint.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ object EndpointWithMultipleOutputTypes extends ZIOAppDefault {
else Left(Quiz("What is the boiling point of water in Celsius?", 2)),
)
})
.toHttpApp).provide(Server.default, Scope.default)
.toRoutes).provide(Server.default, Scope.default)
}
```

Expand Down
18 changes: 9 additions & 9 deletions docs/dsl/flash.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ object NotificationWithoutFlash extends ZIOAppDefault {
}


def run = Server.serve(HttpApp(saveUserRoute, homeRoute))
def run = Server.serve(Routes(saveUserRoute, homeRoute))
.provide(Server.default, ZLayer(Ref.make(List.empty[User])))
}
```
Expand Down Expand Up @@ -350,7 +350,7 @@ val getUsersRoute: Route[Ref[List[User]] with Flash.Backend, Nothing] =
} yield Response.html(html ++ usersHTML)
}

val app = HttpApp(saveUserRoute, getUsersRoute, homeRoute)
val app = Routes(saveUserRoute, getUsersRoute, homeRoute)

def run = Server.serve(app).provide(Server.default, Flash.Backend.inMemory, ZLayer(Ref.make(List.empty[User])))
}
Expand Down Expand Up @@ -520,7 +520,7 @@ object ui {
}

object SetGetBothFlashExample extends ZIOAppDefault {
val httpApp = HttpApp(
val routes = Routes(
Method.GET / "set-flash" -> handler {
val setBoth: Flash.Setter[(String, String)] =
Flash.setNotice("The form was submitted successfully!") ++
Expand All @@ -538,7 +538,7 @@ object SetGetBothFlashExample extends ZIOAppDefault {
},
).sandbox

def run = Server.serve(httpApp).provide(Server.default, Flash.Backend.inMemory)
def run = Server.serve(routes).provide(Server.default, Flash.Backend.inMemory)
}
```

Expand All @@ -555,7 +555,7 @@ import zio._
import zio.http._

object CookieBasedFlashExample extends ZIOAppDefault {
val httpApp = HttpApp(
val routes = Routes(
Method.GET / "set-flash" -> handler {
Response
.seeOther(URL.root / "get-flash")
Expand All @@ -570,7 +570,7 @@ object CookieBasedFlashExample extends ZIOAppDefault {
},
).sandbox

def run = Server.serve(httpApp).provide(Server.default)
def run = Server.serve(routes).provide(Server.default)
}
```

Expand Down Expand Up @@ -609,7 +609,7 @@ import zio.http._
import zio.http.template._

object FlashBackendExample extends ZIOAppDefault {
val httpApp = HttpApp(
val routes = Routes(
Method.GET / "set-flash" -> handler {
for {
flashBackend <- ZIO.service[Flash.Backend]
Expand All @@ -627,7 +627,7 @@ object FlashBackendExample extends ZIOAppDefault {
},
).sandbox

def run = Server.serve(httpApp).provide(Server.default, Flash.Backend.inMemory)
def run = Server.serve(routes).provide(Server.default, Flash.Backend.inMemory)
}
```

Expand All @@ -649,7 +649,7 @@ HTTP/1.1 200 OK
content-type: text/plain
content-length: 28

The form was submitted successfully!
The form was submitted successfully!
```

:::note
Expand Down
34 changes: 17 additions & 17 deletions docs/dsl/handler.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Let's look at some examples of creating handlers, using the `handler` smart cons
import zio._
import zio.http._

HttpApp(
Routes(

// 1. A simple handler that returns a "Hello, World!" response
Method.GET / "hello" ->
Expand Down Expand Up @@ -202,7 +202,7 @@ Let's try an example:
import zio.http._
import zio.stream._

HttpApp(
Routes(
Method.GET / "stream" ->
Handler
.fromStream(
Expand Down Expand Up @@ -239,7 +239,7 @@ Now, let's try another example, this time using `fromStreamChunked`:
import zio.http._
import zio.stream._

HttpApp(
Routes(
Method.GET / "stream" ->
Handler
.fromStreamChunked(
Expand Down Expand Up @@ -273,7 +273,7 @@ import zio.http._
import zio.stream._
import zio.http.template._

HttpApp(
Routes(
Method.GET / "html" ->
Handler.html(

Expand Down Expand Up @@ -320,7 +320,7 @@ ZIP HTTP has a simple built-in template which is useful for creating simple HTML
import zio.http._
import zio.http.template._

HttpApp(
Routes(
Method.GET / "hello" ->
Handler.template("Hello world!")(
html(
Expand Down Expand Up @@ -396,7 +396,7 @@ import zio.http._
import zio.stream._
import zio.schema.codec.JsonCodec.zioJsonBinaryCodec

HttpApp(
Routes(
Method.POST / "bounded-body-consumer" ->
handler { (request: Request) =>
Handler
Expand All @@ -418,7 +418,7 @@ The following example shows how to create a handler that takes an `Int` and `Req
import zio.json._
import zio.http._

HttpApp(
Routes(
Method.GET / "users" / int("userId") ->
Handler.fromFunction[(Int, Request)] { case (userId: Int, request: Request) =>
Response.json(
Expand Down Expand Up @@ -455,7 +455,7 @@ Let's see an example:
import zio.http._
import java.io.File

HttpApp(
Routes(
Method.GET / "video" ->
Handler.fromFile(new File("src/main/resources/TestVideoFile.mp4")),
Method.GET / "text" ->
Expand All @@ -472,7 +472,7 @@ Here is an example:
```scala mdoc:compile-only
import zio.http._

HttpApp(
Routes(
Method.GET / "static" / trailing -> handler {
// Path extractor
val pathExtractor: Handler[Any, Nothing, (Path, Request), Path] =
Expand Down Expand Up @@ -513,7 +513,7 @@ The following example shows how to create an echo server using the `Handler.webS
import zio.http._
import zio.http.ChannelEvent._

HttpApp(
Routes(
Method.GET / "websocket" ->
handler {
Handler.webSocket { channel =>
Expand Down Expand Up @@ -548,7 +548,7 @@ Let's try an example:
```scala mdoc:compile-only
import zio.http._

HttpApp(
Routes(
Method.GET / "stacktrace" ->
handler {
for {
Expand All @@ -575,7 +575,7 @@ To attach a handler aspect to a handler, we use the `@@` operator. For instance,
```scala mdoc:compile-only
import zio.http._

HttpApp(
Routes(
Method.GET / "echo" -> handler { req: Request =>
Handler.fromBody(req.body)
}.flatten @@ HandlerAspect.requestLogging()
Expand All @@ -602,7 +602,7 @@ Let's see an example:
import zio.http._
import java.nio.file._

HttpApp(
Routes(
Method.GET / "file" ->
Handler.fromFile(Paths.get("file.txt").toFile).sandbox,
)
Expand All @@ -612,9 +612,9 @@ In this example, the type of the handler before applying the `sandbox` operator

Without the `sandbox` operator, the compiler would complain about the unhandled `Throwable` error.

### Converting a `Handler` to an `HttpApp`
### Converting a `Handler` to an `Routes`

The `Handler#toHttpApp` operator, converts a handler to an `HttpApp` to be served by the `Server`. The following example, shows an HTTP application that serves a simple "Hello, World!" response for all types of incoming requests:
The `Handler#toRoutes` operator, converts a handler to an `Routes` to be served by the `Server`. The following example, shows an HTTP application that serves a simple "Hello, World!" response for all types of incoming requests:

```scala mdoc:compile-only
import zio._
Expand All @@ -623,7 +623,7 @@ import zio.http._
object HelloWorldServer extends ZIOAppDefault {
def run =
Server
.serve(Handler.fromResponse(Response.text("Hello, world!")).toHttpApp)
.serve(Handler.fromResponse(Response.text("Hello, world!")).toRoutes)
.provide(Server.default)
}
```
Expand Down Expand Up @@ -714,7 +714,7 @@ The are similar to the `ZIO` ones, but they are specialized for the `Handler` ty
The first type parameter of the `Handler` is the environment type. This means that a `Handler` can require an environment to run, like a `ZIO` effect. When we create a `Handler`, we can get access to the environment using `ZIO.service*` methods, and finally, we can provide the environment using `Handler#provide*` methods.

:::note
Please note that in most cases, we are not required to provide the environment of the handler in the middle of the routes definition. It is usually done at the end when we are creating the `HttpApp` using the `Server#serve` method.
Please note that in most cases, we are not required to provide the environment of the handler in the middle of the routes definition. It is usually done at the end when we are creating the `Routes` using the `Server#serve` method.
:::

:::note
Expand Down
4 changes: 2 additions & 2 deletions docs/dsl/handler_aspect.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,10 @@ val statsMiddleware: Middleware[Ref[Map[String, Long]]] =
}
```

After attaching these two handler aspects to our `HttpApp`, we have to provide the initial state for the `Ref[Map[String, Long]]` to the whole application's environment:
After attaching these two handler aspects to our `Routes`, we have to provide the initial state for the `Ref[Map[String, Long]]` to the whole application's environment:

```scala
Server.serve(app @@ counterMiddleware @@ statsMiddleware)
Server.serve(routes @@ counterMiddleware @@ statsMiddleware)
.provide(
Server.default,
ZLayer.fromZIO(Ref.make(Map.empty[String, Long]))
Expand Down
21 changes: 10 additions & 11 deletions docs/dsl/headers.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,15 @@ Response(
```scala mdoc
import Middleware.addHeader

HttpApp(Method.GET / "hello" -> Handler.ok) @@ addHeader(Header.ContentLength(0L))
Routes(Method.GET / "hello" -> Handler.ok) @@ addHeader(Header.ContentLength(0L))
```

### Reading Headers from Request

On the Server-side you can read Request headers as given below:

```scala mdoc
HttpApp(
Routes(
Method.GET / "streamOrNot" -> handler { (req: Request) =>
Response.text(req.headers.map(_.toString).mkString("\n"))
}
Expand All @@ -195,33 +195,32 @@ import zio.stream._

object SimpleResponseDispatcher extends ZIOAppDefault {
override def run =
// Starting the server (for more advanced startup configuration checkout `HelloWorldAdvanced`)
Server.serve(app).provide(Server.default)
// Starting the server (for more advanced startup configuration checkout `HelloWorldAdvanced`)
Server.serve(routes).provide(Server.default)

// Create a message as a Chunk[Byte]
val message = Chunk.fromArray("Hello world !\r\n".getBytes(Charsets.Http))
// Use `Http.collect` to match on route
val app: HttpApp[Any, Response] =
HttpApp(
val routes: Routes[Any, Response] =
Routes(
// Simple (non-stream) based route
Method.GET / "health" -> handler(Response.ok),

// From Request(req), the headers are accessible.
Method.GET / "streamOrNot" ->
handler { (req: Request) =>
Method.GET / "streamOrNot" ->
handler { (req: Request) =>
// Checking if client is able to handle streaming response
val acceptsStreaming: Boolean = req.header(Header.Accept).exists(_.mimeTypes.contains(Header.Accept.MediaTypeWithQFactor(MediaType.application.`octet-stream`, None)))
if (acceptsStreaming)
Response(
status = Status.Ok,
body = Body.fromStream(ZStream.fromChunk(message), message.length.toLong), // Encoding content using a ZStream
)
)
else {
// Adding a custom header to Response
Response(status = Status.Accepted, body = Body.fromChunk(message)).addHeader("X-MY-HEADER", "test")
}
}
).sandbox
).sandbox
}
```

Expand Down
Loading

0 comments on commit a6e9282

Please sign in to comment.