يقدم هذا الفصل كيفية تعامل 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: "Grame",
    Age:  20,
  }

  // الإرجاع باستخدام الدالة الـ json
  return c.JSON(data)
  // => نوع المحتوى: application/json
  // => "{"Name": "Grame", "Age": 20}"

  return c.JSON(fiber.Map{
    "name": "Grame",
    "age": 20,
  })
  // => نوع المحتوى: 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"

  // ...
})

تعيين الكوكيز

تعريف الكوكي

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 = "john"
  cookie.Value = "doe"
  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)
})