Skip to content

Commit 3a39423

Browse files
committed
docs(i18n): guide (zh-cn, ja)
1 parent 77d0eba commit 3a39423

28 files changed

Lines changed: 3457 additions & 0 deletions
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
---
2+
title: バインディング
3+
description: パス、クエリ、header、リクエストボディからリクエストデータを型付き Go struct に解析します。
4+
sidebar:
5+
order: 5
6+
---
7+
8+
リクエストデータの解析は、Web アプリケーションの重要な要素です。Echo ではこれを
9+
_バインディング_ と呼び、HTTP リクエストの 4 つの部分から読み取れます。
10+
11+
- URL パスパラメーター
12+
- URL クエリパラメーター
13+
- Header
14+
- リクエストボディ
15+
16+
## Struct タグによるバインディング
17+
18+
データソースとキーを指定するタグ付きの struct を定義し、そのポインターを
19+
`c.Bind()` に渡します。ここではクエリパラメーター `id``ID` フィールドに
20+
バインドされます。
21+
22+
```go
23+
type User struct {
24+
ID string `query:"id"`
25+
}
26+
27+
// handler for /users?id=<userID>
28+
var user User
29+
if err := c.Bind(&user); err != nil {
30+
return c.String(http.StatusBadRequest, "bad request")
31+
}
32+
```
33+
34+
### データソース
35+
36+
| タグ | ソース |
37+
| -------- | ------ |
38+
| `query` | クエリパラメーター |
39+
| `param` | パスパラメーター |
40+
| `header` | Header 値 |
41+
| `form` | フォームデータ(クエリ + ボディ) |
42+
| `json` | リクエストボディ(`encoding/json`|
43+
| `xml` | リクエストボディ(`encoding/xml`|
44+
45+
パス、クエリ、header、フォームのフィールドには**明示的なタグ**が必要です。
46+
JSON と XML はタグが省略された場合、標準ライブラリと同じように struct フィールド名へ
47+
フォールバックします。
48+
49+
### ボディのコンテンツタイプ
50+
51+
リクエストボディをデコードするときは、`Content-Type` header によってデコーダーが選ばれます。
52+
53+
- `application/json`
54+
- `application/xml`
55+
- `application/x-www-form-urlencoded`
56+
57+
### 複数ソースと優先順位
58+
59+
1 つのフィールドで複数のソースを宣言できます。データは次の順序でバインドされ、
60+
各ステップが前の値を上書きします。
61+
62+
1. パスパラメーター
63+
2. クエリパラメーター(GET / DELETE のみ)
64+
3. リクエストボディ
65+
66+
```go
67+
type User struct {
68+
ID string `param:"id" query:"id" form:"id" json:"id" xml:"id"`
69+
}
70+
```
71+
72+
### 1 つのソースから直接バインドする
73+
74+
```go
75+
echo.BindBody(c, &payload) // request body
76+
echo.BindQueryParams(c, &payload) // query parameters
77+
echo.BindPathValues(c, &payload) // path parameters
78+
echo.BindHeaders(c, &payload) // headers
79+
```
80+
81+
:::note
82+
Header は `c.Bind()`**含まれません**`echo.BindHeaders` で直接バインドしてください。
83+
:::
84+
85+
:::caution[セキュリティ]
86+
ビジネス用の struct に直接バインドしないでください。バインド対象の struct が
87+
`IsAdmin bool` フィールドを公開している場合、`{"IsAdmin": true}` というリクエストボディで
88+
その値が設定されます。専用の DTO を使い、明示的にマッピングしてください。
89+
:::
90+
91+
```go
92+
type UserDTO struct {
93+
Name string `json:"name" form:"name" query:"name"`
94+
Email string `json:"email" form:"email" query:"email"`
95+
}
96+
97+
e.POST("/users", func(c *echo.Context) error {
98+
var dto UserDTO
99+
if err := c.Bind(&dto); err != nil {
100+
return c.String(http.StatusBadRequest, "bad request")
101+
}
102+
user := User{Name: dto.Name, Email: dto.Email, IsAdmin: false}
103+
executeSomeBusinessLogic(user)
104+
return c.JSON(http.StatusOK, user)
105+
})
106+
```
107+
108+
## フルーエントバインディング
109+
110+
単一ソースから明示的かつ型安全にバインドするには、フルーエント binder を使います。
111+
設定をチェーンし、実行時にエラーを収集します。
112+
113+
```go
114+
// /api/search?active=true&id=1&id=2&id=3&length=25
115+
var opts struct {
116+
IDs []int64
117+
Active bool
118+
}
119+
length := int64(50)
120+
121+
err := echo.QueryParamsBinder(c).
122+
Int64("length", &length).
123+
Int64s("id", &opts.IDs).
124+
Bool("active", &opts.Active).
125+
BindError() // first error, if any
126+
```
127+
128+
利用できる binder は `echo.QueryParamsBinder(c)``echo.PathValuesBinder(c)`
129+
`echo.FormFieldBinder(c)` です。チェーンは `BindError()`(最初のエラー)または
130+
`BindErrors()`(すべてのエラー)で終了します。`FailFast(false)` はチェーン全体を実行します。
131+
デフォルトでは早期終了が有効です。
132+
133+
各サポート型には `Type(...)``MustType(...)``Types(...)`(スライス)、
134+
`MustTypes(...)` メソッドがあります。例:`Int64``MustInt64``Int64s`
135+
カンマ区切りの値を分割するには `BindWithDelimiter("id", &dest, ",")` を使います。
136+
137+
## カスタム binder
138+
139+
`Echo#Binder` でカスタム binder を登録します。
140+
141+
```go
142+
type CustomBinder struct{}
143+
144+
func (cb *CustomBinder) Bind(c *echo.Context, i any) error {
145+
db := new(echo.DefaultBinder)
146+
if err := db.Bind(c, i); err != echo.ErrUnsupportedMediaType {
147+
return err
148+
}
149+
// custom logic here
150+
return nil
151+
}
152+
153+
e.Binder = &CustomBinder{}
154+
```
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
---
2+
title: コンテキスト
3+
description: リクエスト、レスポンス、パラメーター、ヘルパーを保持するリクエストごとのオブジェクトです。
4+
sidebar:
5+
order: 4
6+
---
7+
8+
`echo.Context` は現在の HTTP リクエストのコンテキストを表します。そのポインター
9+
`*echo.Context`)はすべてのハンドラとミドルウェアに渡され、リクエストとレスポンス、
10+
パスパラメーター、バインド済みデータ、レスポンス作成用のヘルパーを保持します。
11+
12+
```go
13+
func handler(c *echo.Context) error {
14+
// ...
15+
return nil
16+
}
17+
```
18+
19+
## 入力を読む
20+
21+
```go
22+
id := c.Param("id") // path parameter
23+
q := c.QueryParam("q") // query string value
24+
all := c.QueryParams() // url.Values of all query params
25+
name := c.FormValue("name") // form field (URL + body)
26+
ua := c.Request().Header.Get(echo.HeaderUserAgent)
27+
```
28+
29+
値が存在しない場合にデフォルト値を返す、対応する `*Or` ヘルパーもあります。
30+
`c.ParamOr("id", "0")``c.QueryParamOr("page", "1")``c.FormValueOr(...)`
31+
などです。
32+
33+
## レスポンスを書く
34+
35+
```go
36+
c.String(http.StatusOK, "plain text")
37+
c.JSON(http.StatusOK, payload)
38+
c.JSONPretty(http.StatusOK, payload, " ")
39+
c.HTML(http.StatusOK, "<b>hi</b>")
40+
c.XML(http.StatusOK, payload)
41+
c.Blob(http.StatusOK, "application/pdf", bytes)
42+
c.Stream(http.StatusOK, "application/octet-stream", reader)
43+
c.NoContent(http.StatusNoContent)
44+
c.Redirect(http.StatusFound, "/elsewhere")
45+
```
46+
47+
## ファイル
48+
49+
```go
50+
c.File("public/report.pdf") // serve a file
51+
c.Attachment("invoice.pdf", "inv.pdf") // prompt download
52+
c.Inline("photo.png", "photo.png") // render inline
53+
```
54+
55+
## リクエストごとのストレージ
56+
57+
`Get`/`Set` を使ってミドルウェアとハンドラの間でデータを共有します。
58+
59+
```go
60+
c.Set("user", u)
61+
u, _ := c.Get("user").(*User)
62+
```
63+
64+
ジェネリクスヘルパーで型付きアクセスもできます。
65+
66+
```go
67+
u, err := echo.ContextGet[*User](c, "user")
68+
```
69+
70+
## バインディングと検証
71+
72+
`c.Bind()` はリクエストデータを struct に解析します。詳しくは
73+
[バインディング](/ja/guide/binding/)を参照してください。
74+
75+
```go
76+
var dto CreateUser
77+
if err := c.Bind(&dto); err != nil {
78+
return echo.ErrBadRequest
79+
}
80+
```
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
---
2+
title: Cookie
3+
description: 標準の http.Cookie 型を使って HTTP Cookie を作成、読み取り、一覧表示します。
4+
sidebar:
5+
order: 11
6+
---
7+
8+
Cookie はサーバーがブラウザーに送信する小さなデータで、ブラウザーはそれを保存し、
9+
後続のリクエストで送り返します。Cookie により、ショッピングカート、認証状態、
10+
以前入力したフォーム値などの状態を Web サイトが記憶できます。
11+
12+
Echo は Go 標準の `http.Cookie` 型を使い、ハンドラ内の `echo.Context` から
13+
Cookie を追加および取得します。
14+
15+
## Cookie 属性
16+
17+
| 属性 | 任意 |
18+
| ---------- | ---- |
19+
| `Name` | いいえ |
20+
| `Value` | いいえ |
21+
| `Path` | はい |
22+
| `Domain` | はい |
23+
| `Expires` | はい |
24+
| `Secure` | はい |
25+
| `HttpOnly` | はい |
26+
27+
## Cookie を作成する
28+
29+
```go
30+
func writeCookie(c *echo.Context) error {
31+
cookie := new(http.Cookie)
32+
cookie.Name = "username"
33+
cookie.Value = "jon"
34+
cookie.Expires = time.Now().Add(24 * time.Hour)
35+
c.SetCookie(cookie)
36+
return c.String(http.StatusOK, "write a cookie")
37+
}
38+
```
39+
40+
- `new(http.Cookie)` で Cookie を作成します。
41+
- `http.Cookie` フィールドに属性を設定します。
42+
- `c.SetCookie(cookie)` を呼び出して、レスポンスに `Set-Cookie` header を追加します。
43+
44+
## Cookie を読む
45+
46+
```go
47+
func readCookie(c *echo.Context) error {
48+
cookie, err := c.Cookie("username")
49+
if err != nil {
50+
return err
51+
}
52+
fmt.Println(cookie.Name)
53+
fmt.Println(cookie.Value)
54+
return c.String(http.StatusOK, "read a cookie")
55+
}
56+
```
57+
58+
- `c.Cookie("username")` で名前から Cookie を読み取ります。
59+
- `http.Cookie` フィールドを通じて属性にアクセスします。
60+
61+
## すべての Cookie を読む
62+
63+
```go
64+
func readAllCookies(c *echo.Context) error {
65+
for _, cookie := range c.Cookies() {
66+
fmt.Println(cookie.Name)
67+
fmt.Println(cookie.Value)
68+
}
69+
return c.String(http.StatusOK, "read all the cookies")
70+
}
71+
```
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
title: カスタマイズ
3+
description: Echo の logger、validator、binder、renderer、serializer、エラー処理をカスタマイズします。
4+
sidebar:
5+
order: 12
6+
---
7+
8+
Echo は `Echo` インスタンス上に一連のフィールドを公開しており、組み込みの挙動を
9+
独自実装に置き換えられます。
10+
11+
## ログ
12+
13+
`Echo#Logger` は構造化ログを書き込みます。デフォルトのハンドラは JSON を
14+
`os.Stdout` に出力します。
15+
16+
### カスタム logger
17+
18+
logger は `*slog.Logger` なので、任意の `slog` ハンドラを登録できます。
19+
20+
```go
21+
e.Logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
22+
```
23+
24+
## Validator
25+
26+
`Echo#Validator` はリクエストペイロード検証用の validator を登録します。
27+
28+
[詳しく見る](/ja/guide/request/#validate-data)
29+
30+
## カスタム binder
31+
32+
`Echo#Binder` はリクエストペイロードをバインドするカスタム binder を登録します。
33+
34+
[詳しく見る](/ja/guide/binding/#custom-binder)
35+
36+
## カスタム JSON serializer
37+
38+
`Echo#JSONSerializer` はカスタム JSON serializer を登録します。
39+
[json.go](https://github.com/labstack/echo/blob/master/json.go)
40+
`DefaultJSONSerializer` を参照してください。
41+
42+
## Renderer
43+
44+
`Echo#Renderer` はテンプレートレンダリング用の renderer を登録します。
45+
46+
[詳しく見る](/ja/guide/templates/)
47+
48+
## HTTP エラーハンドラ
49+
50+
`Echo#HTTPErrorHandler` はカスタム HTTP エラーハンドラを登録します。
51+
52+
[詳しく見る](/ja/guide/error-handling/)
53+
54+
## ルートコールバック
55+
56+
`Echo#OnAddRoute` は、新しいルートがルーターに追加されるたびに呼び出される
57+
コールバックを登録します。
58+
59+
## IP 抽出器
60+
61+
`Echo#IPExtractor` は実際のクライアント IP アドレスをどう判定するかを制御します。
62+
信頼性と安全性を保って取得するには、アプリケーションがインフラ全体を把握している必要があります。
63+
64+
[詳しく見る](/ja/guide/ip-address/)

0 commit comments

Comments
 (0)