Bu bölüm, Go Fiber'ın isteği ve yanıtı nasıl işlediğini tanıtıyor, genellikle mevcut API geliştirmeleri için JSON verilerini döndürerek.
Fiber çerçevesi genellikle Ctx
bağlam nesnesinin dönüş verilerini kullanır.
JSON Veri Döndürme
type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c *fiber.Ctx) error {
// Yanıt için veri yapısı oluştur
data := SomeStruct{
Name: "Grame",
Age: 20,
}
// json fonksiyonunu kullanarak dön
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 Formatında Veri Döndürme
type SomeStruct struct {
name string
age uint8
}
app.Get("/", func(c *fiber.Ctx) error {
// Veri yapısı oluştur
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})
})
Metin Döndürme
app.Get("/", func(c *fiber.Ctx) error {
// "Hello, World ?!" ifadesini bir dize olarak döndür
return c.SendString("Hello, World ?!")
})
Durum Kodu Döndürme
app.Get("/not-found", func(c *fiber.Ctx) error {
// Yanıt durum kodunu ayarla
return c.SendStatus(415)
// => 415 "Desteklenmeyen medya tipi"
c.SendString("Hello, World!")
// Yanıt durum kodunu ayarla
return c.SendStatus(415)
// => 415 "Hello, World!"
})
Dosyaları Döndürme (Dosya İndirme Uygulama)
app.Get("/", func(c *fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => rapor-12345.pdf indir
return c.Download("./files/report-12345.pdf", "rapor.pdf");
// => rapor.pdf indir
})
İsteğe Başlıklar Ayarlama
app.Get("/", func(c *fiber.Ctx) error {
c.Set("Content-Type", "text/plain")
// => "İçerik türü: düz metin"
// ...
})
Çerez Ayarlama
Çerez tanımı
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"`
}
Çerez Dönüşü
app.Get("/", func(c *fiber.Ctx) error {
// Çerez oluştur
cookie := new(fiber.Cookie)
cookie.Name = "john"
cookie.Value = "doe"
cookie.Expires = time.Now().Add(24 * time.Hour)
// Çerezi ayarla
c.Cookie(cookie)
// ...
})
Yönlendirme (301 veya 302)
Varsayılan olarak 302 yönlendirmesi
app.Get("/", func(c *fiber.Ctx) error {
return c.Redirect("/foo/bar")
return c.Redirect("../giriş")
return c.Redirect("http://example.com")
return c.Redirect("http://example.com", 301)
})