บทนี้จะแนะนำวิธีการจัดการคำขอและการตอบกลับของ Go Fiber โดยทั่วไปโดยการส่งค่า JSON สำหรับการพัฒนา API ปัจจุบัน
Fiber framework ใช้ข้อมูลที่ส่งกลับจาก Ctx
object โดยส่วนใหญ่
การส่งค่า 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)
// => 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
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)
})