یہ باب پیش کرتا ہے کہ گو فائبر کیسے درخواست اور جواب کو منظم کرتا ہے، عام طور پر موجودہ API تیاری کے لئے JSON ڈیٹا واپس کر کے۔
فائبر فریم ورک بنیادی طور پر 'کونٹیکسٹ' شے کے واپسی ڈیٹا استعمال کرتا ہے۔
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")
// => "مواد کی قسم: 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)
})