0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概要

このブログでは、ZIO HTTPを使ったシンプルな"Hello, World!"アプリケーションの作成方法を紹介します。

サンプルコード

以下のコードは、zio-httpを使用してHTTPサーバーを構築し、/helloエンドポイントに対して"Hello, World!"というレスポンスを返すアプリケーションの例です。

import zio._
import zio.http._

object Main extends ZIOAppDefault {
  val routes: Routes[Any, Response] =
    Routes(
      Method.GET / "hello" ->
        handler(Response.text("Hello, World!"))
    )

  def run: ZIO[Any, Throwable, Nothing] = {
    Server.serve(routes).provide(Server.default)
  }
}

コードの詳細

ルーティングの定義

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

この部分では、HTTP GETリクエストが/helloに対して行われたときに、"Hello, World!"というテキストレスポンスを返すようにルーティングを定義しています。

サーバーの起動

def run: ZIO[Any, Throwable, Nothing] = {
  Server.serve(routes).provide(Server.default)
}

runメソッドでは、サーバーを起動するための処理を定義しています。ここで重要なのは、Server.serve(routes)の部分です。このメソッドは、指定されたルーティングに基づいてサーバーを起動します。

Server.serveの戻り値

Server.serveメソッドの戻り値はURIO[Server, Nothing]です。URIOは型エイリアスでZIO[Server, Nothing, Nothing]とも表現できます。この型は、Serverを要求し、失敗しないことを示しています。

provideによる依存関係の注入

Server.serve(routes).provide(Server.default)

provideメソッドを使用することで、Serverを注入しています。ここでは、Server.defaultが注入されます。

Server.defaultとは

Server.defaultは、デフォルトのサーバー設定を提供するためのものです。この設定には、標準的なポート(通常は8080)やホスト名(通常はlocalhost)が含まれます。開発中はこのデフォルト設定で十分ですが、本番環境ではカスタマイズが必要な場合があります。

まとめ

このブログでは、zio-httpを使用してシンプルなHello, Worldアプリケーションを作成する方法を紹介しました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?