# Handlers

- [Introduction](#introduction)
- [Writing handlers](#writing-handlers)
    - [Basic handlers](#basic-handlers)
    - [Handlers and routes](#handlers-and-routes)
- [Reading the request](#reading-the-request)
- [Handlers with dependencies](#handlers-with-dependencies)
- [Standard handlers](#standard-handlers)

<a name="introduction"></a>

## Introduction


ルートファイルにすべての処理を関数リテラルで書く代わりに、ハンドラーへ整理できます。ハンドラーはリクエストを受け取りレスポンスを返す関数で、関連するものを同じパッケージにまとめます。例えば `posts` パッケージに投稿の一覧、表示、作成のハンドラーを置きます。これらのパッケージは `handlers` ディレクトリに配置します。

<a name="writing-handlers"></a>

## Writing handlers

<a name="basic-handlers"></a>

### Basic handlers


ハンドラーは [request](/ja/go/docs/requests) から必要な情報を読み、[response](/ja/go/docs/responses) を返します。以下は `handlers/posts/posts.go` の `posts` パッケージです。`Index` が全投稿を一覧し、`Show` が一件を表示し、`Store` が送信されたフォームから投稿を作成します。

```go
package posts

import (
	"go.laravel.com/inertia"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
)

type NewPost struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

func (f *NewPost) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Title, rule.Required, rule.Max(255)),
		rule.Field(&f.Body, rule.Required),
	)
}

func Index(r *web.Request) *web.Response {
	posts, err := model.Query[models.Post]().Latest("created_at").Get(r)
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Index", inertia.Props{"posts": posts})
}

func Show(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Show", inertia.Props{"post": post})
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[NewPost]()
	if err != nil {
		return web.Fail(err)
	}

	post := models.Post{Title: form.Title, Body: form.Body}
	if err := model.Create(r, &post); err != nil {
		return web.Fail(err)
	}

	return web.RedirectRoute("posts.show", "post", &post)
}
```


各ハンドラーはリクエストから必要な情報だけを読み取ります。


- `Show` は `/posts/42` の投稿 42 のように [post that the route's path names](/ja/go/docs/models#finding-a-model-from-a-route) を探します。その ID がなければ `model.FromRoute` がエラーを返し、`web.Fail` が `404` ページで応答します。
- `Store` はフォーム入力を `NewPost` として [validates](/ja/go/docs/validation) します。無効なら `web.Fail` がエラーとともにフォームへ戻します。有効なら `Store` が投稿を作成し、新しい投稿ページへリダイレクトします。


クエリ失敗などのエラーを受け取ると、ハンドラーは `web.Fail(err)` を返します。Laravel はエラーをページなどのレスポンスへ [renders](/ja/go/docs/errors) し、サーバーエラーなら報告します。閲覧権限のないユーザーへの `403` など独自のステータスには `web.Abort(http.StatusForbidden)` を返します。詳しくは [HTTP errors](/ja/go/docs/errors#http-errors) を参照してください。

<a name="handlers-and-routes"></a>

### Handlers and routes


ハンドラーを書いたら `routes/web.go` などでルートから参照します。リクエストがパスに一致すると、Laravel は本文を読み込んでハンドラーを呼び出します。

```go
package routes

import (
	"go.laravel.com/config"
	"go.laravel.com/routing"

	"app/handlers/posts"
)

func Web(route *routing.Router, cfg *config.Config) {
	route.Get("/posts", posts.Index).Name("posts.index")
	route.Get("/posts/{post}", posts.Show).Name("posts.show")
	route.Post("/posts", posts.Store).Name("posts.store")
}
```


ルート名があれば、パスを繰り返さずに他の場所からリンクできます。例えば `urls.Route(r, "posts.show", "post", &post)` は `http://example.com/posts/42` のような URL を返します。詳しくは [named routes](/ja/go/docs/routing#named-routes) を参照してください。


投稿の作成など、一部のハンドラーはログイン済みユーザーなど特定のユーザーにだけ許可すべきです。実行前に検査するにはルートへ [middleware](/ja/go/docs/middleware#assigning-middleware-to-routes) を付けます。例えば `auth.Authenticate` はゲストをログインページへ送ります。

```go
import "go.laravel.com/auth"

route.Post("/posts", posts.Store).Name("posts.store").Middleware(auth.Authenticate{})
```


多くのパッケージはモデルの一覧、作成、表示、変更、削除を行う `Index`、`Create`、`Store`、`Show`、`Edit`、`Update`、`Destroy` を持ちます。個別にルートを登録せず、`route.Resource` でまとめて登録できます。詳しくは [resource routes](/ja/go/docs/routing#resource-routes) を参照してください。

<a name="reading-the-request"></a>

## Reading the request


すべてのハンドラーは `func(r *web.Request) *web.Response` という署名を持ち、`r` から情報を読みます。Go の `*http.Request` を埋め込むため、`r.Header`、`r.URL`、`r.PathValue` は標準のものです。また [context](/ja/go/docs/context) でもあるので、クエリなど待機する処理には `r` を渡してください。訪問者がページを閉じるなど、[when the request ends](/ja/go/docs/context#when-a-request-ends) に該当するとクエリが止まります。


ハンドラーでよく使う呼び出しは次のとおりです。

| 呼び出し | 戻り値 |
| --- | --- |
| `model.FromRoute[models.Post](r, "post")` | [route parameter](/ja/go/docs/models#finding-a-model-from-a-route) が指すモデル、または `404` で応答するエラー。 |
| `r.User[models.User]()` | [logged-in user](/ja/go/docs/authentication#retrieving-the-logged-in-user)、またはゲストなら nil。 |
| `r.Validate[NewPost]()` | 構造体へ [validated](/ja/go/docs/validation) したリクエスト本文の入力。 |
| `r.Query[PostFilters]()` | 構造体へ解析した [query string](/ja/go/docs/requests#query-string-input)。 |
| `r.PathValue("post")` | 文字列の [route parameter](/ja/go/docs/routing#route-parameters)。 |
| `r.Session()` | `web` グループのリクエストの [session](/ja/go/docs/session)。 |
| `services.From(r)` | アプリケーションの [services](#handlers-with-dependencies)。 |


Laravel はハンドラー実行前に本文を読むため、不正な形式や大きすぎる本文はコードに届く前に失敗します。その後はユーザー、ルートのモデル、入力を任意の順序で何度でも取得できます。例えば次の `auth.Authenticate` 配下のハンドラーは、検証したフォームでユーザーのプロフィールを更新し、元のページへ戻します。

```go
package profile

import (
	"go.laravel.com/db"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
)

type EditProfile struct {
	Name string `json:"name"`
}

func (f *EditProfile) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Name, rule.Required, rule.Max(255)),
	)
}

func Update(r *web.Request) *web.Response {
	user := r.User[models.User]()

	form, err := r.Validate[EditProfile]()
	if err != nil {
		return web.Fail(err)
	}

	if err := model.Update(r, user, db.Values{"name": form.Name}); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}
```


`*http.Request` を埋め込むため `r.FormValue` などの標準メソッドも呼べます。ただし `r.FormValue` や `r.Body` の直接デコードより、`r.Validate` と上記の入力メソッドを推奨します。標準メソッドは空の値や、ハンドラーで応答に変換すべきエラーを返すため、ユーザーは入力の問題を確認できません。`r.Validate` ならリダイレクト後のフォームや JSON クライアントへエラーが返ります。

<a name="handlers-with-dependencies"></a>

## Handlers with dependencies


多くのハンドラーは決済クライアントや検索インデックスなど、リクエストより長く生きる要素を必要とします。これが [services](/ja/go/docs/services) です。Laravel は起動時に [your settings](/ja/go/docs/configuration#your-own-settings) から作成し、ハンドラーは `services.From(r)` で取得します。次の例は請求サービスからユーザーの請求書を一覧します。

```go
package invoices

import (
	"go.laravel.com/web"

	"app/services"
)

func Index(r *web.Request) *web.Response {
	invoices, err := services.From(r).Billing.Invoices(r)
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(invoices)
}
```


ミドルウェアも受け取ったリクエストで `services.From(r)` を呼びます。ハンドラー以下の関数は `ctx context.Context` を受け取り `services.From(ctx)` を使うため、ジョブやコマンドからも動作します。パッケージのサービスは `inspire.From(r)` など、そのパッケージから取得します。詳しくは [services](/ja/go/docs/packages#services) を参照してください。


テストでは、課金しない決済クライアントなどの fake にサービスを置き換えられます。テストが作るアプリケーションごとに独立したサービスを持つため、後で戻す必要はありません。[replacing dependencies](/ja/go/docs/testing#replacing-dependencies) を参照してください。


ログインユーザーなど一つのリクエストに属する値はサービスではなく、リクエストのコンテキストに保持します。サブドメインが指すチームなど独自の値をミドルウェアで追加するには、[adding values of your own](/ja/go/docs/context#adding-values-of-your-own) を参照してください。

<a name="standard-handlers"></a>

## Standard handlers


Go の多くのライブラリは `net/http` 向けで、Prometheus メトリクスやリバースプロキシなどの `http.Handler` を提供します。アプリケーションで提供するには `route.Handle` でマウントします。そのパスのすべてのメソッドへ応答します。

```go
import (
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"go.laravel.com/config"
	"go.laravel.com/routing"
)

func Web(route *routing.Router, cfg *config.Config) {
	route.Handle("/metrics", promhttp.Handler())
}
```


ルートのミドルウェアは実行されるため、標準ハンドラーにも `auth.Authenticate` を適用できます。Laravel は本文を読まず、標準ハンドラーが直接読み込めるようにします。


一つのメソッド用にマウントするには、`http.ServeMux` と同様にパターンの先頭へメソッドを付けます。例えば決済ライブラリが `POST` 用の `webhook` ハンドラーを提供する場合があります。

```go
route.Handle("POST /webhooks/stripe", webhook)
```


`route.Post` はハンドラー前にフォーム本文を読むため、標準ハンドラーには `route.Post` でなく `route.Handle` を使います。標準ミドルウェアについては [standard middleware](/ja/go/docs/middleware#standard-middleware) を参照してください。


アプリケーション自体も `http.Handler` です。そのため、`laravel.New` の戻り値を独自の `http.Server` で提供したり、大きなプログラム内へマウントしたりできます。