इस अध्याय में हम जानेंगे कि Go Fiber कैसे अनुरोध और प्रतिक्रिया को संभालता है, जिसका प्रमुखतः उपयोग वर्तमान API विकास के लिए JSON डेटा वापस करके किया जाता है।

Fiber framework प्राथमिक रूप से Ctx context object के वापसी डेटा का उपयोग करता है।

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 {
        // "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");
  // => रिपोर्ट-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 = "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)
})