この章では、Go Fiberがリクエストとレスポンスをどのように処理するかを紹介します。通常、現在のAPI開発ではJSONデータを返します。
Fiberフレームワークでは主にCtx
コンテキストオブジェクトの戻りデータを使用します。
JSONデータの返却
type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c *fiber.Ctx) error {
// レスポンス用のデータ構造体を作成
data := SomeStruct{
Name: "Grame",
Age: 20,
}
// json関数を使用して返却
return c.JSON(data)
// => Content-Type: application/json
// => "{"Name": "Grame", "Age": 20}"
return c.JSON(fiber.Map{
"name": "Grame",
"age": 20,
})
// => Content-Type: application/json
// => "{"name": "Grame", "age": 20}"
})
JSONP形式の返却
type SomeStruct struct {
name string
age uint8
}
app.Get("/", func(c *fiber.Ctx) error {
// データ構造体を作成
data := SomeStruct{
name: "Grame",
age: 20,
}
return c.JSONP(data)
// => callback({"name": "Grame", "age": 20})
return c.JSONP(data, "customFunc")
// => customFunc({"name": "Grame", "age": 20})
})
テキストの返却
app.Get("/", func(c *fiber.Ctx) error {
// 文字列として "Hello, World ?!" を返却
return c.SendString("Hello, World ?!")
})
ステータスコードの返却
app.Get("/not-found", func(c *fiber.Ctx) error {
// レスポンスステータスコードを設定
return c.SendStatus(415)
// => 415 "Unsupported Media Type"
c.SendString("Hello, World!")
// レスポンスステータスコードを設定
return c.SendStatus(415)
// => 415 "Hello, World!"
})
ファイルの返却(ファイルのダウンロードを実装)
app.Get("/", func(c *fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => report-12345.pdfをダウンロード
return c.Download("./files/report-12345.pdf", "report.pdf");
// => report.pdfをダウンロード
})
リクエストヘッダーの設定
app.Get("/", func(c *fiber.Ctx) error {
c.Set("Content-Type", "text/plain")
// => "Content-type: text/plain"
// ...
})
Cookieの設定
Cookieの定義
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path"`
Domain string `json:"domain"`
MaxAge int `json:"max_age"`
Expires time.Time `json:"expires"`
Secure bool `json:"secure"`
HTTPOnly bool `json:"http_only"`
SameSite string `json:"same_site"`
SessionOnly bool `json:"session_only"`
}
Cookieの返却
app.Get("/", func(c *fiber.Ctx) error {
// Cookieを作成
cookie := new(fiber.Cookie)
cookie.Name = "john"
cookie.Value = "doe"
cookie.Expires = time.Now().Add(24 * time.Hour)
// Cookieを設定
c.Cookie(cookie)
// ...
})
リダイレクト(301または302)
デフォルトは302リダイレクト
app.Get("/", func(c *fiber.Ctx) error {
return c.Redirect("/foo/bar")
return c.Redirect("../login")
return c.Redirect("http://example.com")
return c.Redirect("http://example.com", 301)
})