コンテキスト
echo.Context は現在の HTTP リクエストのコンテキストを表します。そのポインター
(*echo.Context)はすべてのハンドラとミドルウェアに渡され、リクエストとレスポンス、
パスパラメーター、バインド済みデータ、レスポンス作成用のヘルパーを保持します。
func handler(c *echo.Context) error { // ... return nil}id := c.Param("id") // path parameterq := c.QueryParam("q") // query string valueall := c.QueryParams() // url.Values of all query paramsname := c.FormValue("name") // form field (URL + body)ua := c.Request().Header.Get(echo.HeaderUserAgent)値が存在しない場合にデフォルト値を返す、対応する *Or ヘルパーもあります。
c.ParamOr("id", "0")、c.QueryParamOr("page", "1")、c.FormValueOr(...)
などです。
レスポンスを書く
Section titled “レスポンスを書く”c.String(http.StatusOK, "plain text")c.JSON(http.StatusOK, payload)c.JSONPretty(http.StatusOK, payload, " ")c.HTML(http.StatusOK, "<b>hi</b>")c.XML(http.StatusOK, payload)c.Blob(http.StatusOK, "application/pdf", bytes)c.Stream(http.StatusOK, "application/octet-stream", reader)c.NoContent(http.StatusNoContent)c.Redirect(http.StatusFound, "/elsewhere")c.File("public/report.pdf") // serve a filec.Attachment("invoice.pdf", "inv.pdf") // prompt downloadc.Inline("photo.png", "photo.png") // render inlineリクエストごとのストレージ
Section titled “リクエストごとのストレージ”Get/Set を使ってミドルウェアとハンドラの間でデータを共有します。
c.Set("user", u)u, _ := c.Get("user").(*User)ジェネリクスヘルパーで型付きアクセスもできます。
u, err := echo.ContextGet[*User](c, "user")バインディングと検証
Section titled “バインディングと検証”c.Bind() はリクエストデータを struct に解析します。詳しくは
バインディングを参照してください。
var dto CreateUserif err := c.Bind(&dto); err != nil { return echo.ErrBadRequest}