این فصل نحوه پردازش درخواست و پاسخ در Go Fiber را معرفی می‌کند که به طور معمول با بازگشت دادن داده‌های JSON برای توسعه API فعلی استفاده می‌شود.

فریمورک Fiber اصولاً از داده‌های بازگشتی شیء محیط Ctx استفاده می‌کند.

بازگردانی داده‌های JSON

type SomeStruct struct {
  Name string
  Age  uint8
}

app.Get("/json", func(c *fiber.Ctx) error {
  // ایجاد ساختار داده برای پاسخ
  data := SomeStruct{
    Name: "گریم",
    Age: 20,
  }

  // با استفاده از تابع json بازگردانی کنید
  return c.JSON(data)
  // => Content-Type: application/json
  // => "{"Name": "گریم", "Age": 20}"

  return c.JSON(fiber.Map{
    "name": "گریم",
    "age": 20,
  })
  // => Content-Type: application/json
  // => "{"name": "گریم", "age": 20}"
})

بازگشت فرمت JSONP

type SomeStruct struct {
  name string
  age  uint8
}

app.Get("/", func(c *fiber.Ctx) error {
  // ایجاد ساختار داده
  data := SomeStruct{
    name: "گریم",
    age: 20,
  }

  return c.JSONP(data)
  // => callback({"name": "گریم", "age": 20})

  return c.JSONP(data, "customFunc")
  // => customFunc({"name": "گریم", "age": 20})
})

بازگشت متن

app.Get("/", func(c *fiber.Ctx) error {
        // بازگردانی "سلام، دنیا ?!" به صورت رشته
        return c.SendString("سلام، دنیا ?!")
})

بازگشت کد وضعیت

app.Get("/not-found", func(c *fiber.Ctx) error {
  // تنظیم کد وضعیت پاسخ
  return c.SendStatus(415)
  // => 415 "نوع رسانه پشتیبانی نشده"

  c.SendString("سلام، دنیا!")
  // تنظیم کد وضعیت پاسخ
  return c.SendStatus(415)
  // => 415 "سلام، دنیا!"
})

بازگشت فایل (اجرای دانلود فایل)

app.Get("/", func(c *fiber.Ctx) error {
  return c.Download("./files/report-12345.pdf");
  // => دانلود گزارش-12345.pdf

  return c.Download("./files/report-12345.pdf", "report.pdf");
  // => دانلود گزارش.pdf
})

تنظیم هدرهای درخواست

app.Get("/", func(c *fiber.Ctx) error {
  c.Set("Content-Type", "text/plain")
  // => "Content-type: text/plain"

  // ...
})

تنظیم کوکی

تعریف کوکی

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"`
}

بازگشت کوکی

app.Get("/", func(c *fiber.Ctx) error {
  // ایجاد کوکی
  cookie := new(fiber.Cookie)
  cookie.Name = "جان"
  cookie.Value = "دو"
  cookie.Expires = time.Now().Add(24 * time.Hour)

  // تنظیم کوکی
  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)
})