Chương này giới thiệu cách Go Fiber xử lý yêu cầu và phản hồi, thông thường bằng cách trả về dữ liệu JSON cho việc phát triển API hiện tại.

Khung việc sử dụng dữ liệu trả về của đối tượng ngữ cảnh Ctx.

Trả về Dữ liệu JSON

type SomeStruct struct {
  Name string
  Age  uint8
}

app.Get("/json", func(c *fiber.Ctx) error {
  // Tạo cấu trúc dữ liệu cho phản hồi
  data := SomeStruct{
    Name: "Grame",
    Age:  20,
  }

  // Trả về bằng cách sử dụng hàm 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}"
})

Trả về Định dạng JSONP

type SomeStruct struct {
  name string
  age  uint8
}

app.Get("/", func(c *fiber.Ctx) error {
  // Tạo cấu trúc dữ liệu
  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})
})

Trả về Văn bản

app.Get("/", func(c *fiber.Ctx) error {
        // Trả về "Xin chào, Thế giới ?!" dưới dạng chuỗi
        return c.SendString("Xin chào, Thế giới ?!")
})

Trả về Mã trạng thái

app.Get("/not-found", func(c *fiber.Ctx) error {
  // Thiết lập mã trạng thái phản hồi
  return c.SendStatus(415)
  // => 415 "Unsupported Media Type"

  c.SendString("Xin chào, Thế giới!")
  // Thiết lập mã trạng thái phản hồi
  return c.SendStatus(415)
  // => 415 "Xin chào, Thế giới!"
})

Trả về Tệp (Thực hiện Tải xuống Tệp)

app.Get("/", func(c *fiber.Ctx) error {
  return c.Download("./files/report-12345.pdf");
  // => Tải xuống report-12345.pdf

  return c.Download("./files/report-12345.pdf", "report.pdf");
  // => Tải xuống report.pdf
})

Thiết lập Tiêu đề Yêu cầu

app.Get("/", func(c *fiber.Ctx) error {
  c.Set("Content-Type", "text/plain")
  // => "Content-type: text/plain"

  // ...
})

Thiết lập Cookie

Định nghĩa Cookie

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"`
}

Trả về Cookie

app.Get("/", func(c *fiber.Ctx) error {
  // Tạo cookie
  cookie := new(fiber.Cookie)
  cookie.Name = "john"
  cookie.Value = "doe"
  cookie.Expires = time.Now().Add(24 * time.Hour)

  // Thiết lập cookie
  c.Cookie(cookie)
  // ...
})

Chuyển hướng (301 hoặc 302)

Mặc định là chuyển hướng 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)
})