Este capítulo apresenta como o Go Fiber lida com solicitações e respostas, geralmente retornando dados JSON para o desenvolvimento atual da API.

O framework Fiber usa principalmente os dados de retorno do objeto de contexto Ctx.

Retornando Dados JSON

type SomeStruct struct {
  Name string
  Age  uint8
}

app.Get("/json", func(c *fiber.Ctx) error {
  // Criar estrutura de dados para resposta
  data := SomeStruct{
    Name: "Grame",
    Age:  20,
  }

  // Retornar usando a função 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}"
})

Retornando Formato JSONP

type SomeStruct struct {
  name string
  age  uint8
}

app.Get("/", func(c *fiber.Ctx) error {
  // Criar estrutura de dados
  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})
})

Retornando Texto

app.Get("/", func(c *fiber.Ctx) error {
        // Retornar "Olá, Mundo ?!" como uma string
        return c.SendString("Olá, Mundo ?!")
})

Retornando Código de Status

app.Get("/not-found", func(c *fiber.Ctx) error {
  // Definir o código de status da resposta
  return c.SendStatus(415)
  // => 415 "Tipo de Mídia Não Suportado"

  c.SendString("Olá, Mundo!")
  // Definir o código de status da resposta
  return c.SendStatus(415)
  // => 415 "Olá, Mundo!"
})

Retornando Arquivos (Implementar o Download de Arquivos)

app.Get("/", func(c *fiber.Ctx) error {
  return c.Download("./files/report-12345.pdf");
  // => Baixar report-12345.pdf

  return c.Download("./files/report-12345.pdf", "report.pdf");
  // => Baixar report.pdf
})

Definindo Cabeçalhos da Solicitação

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

  // ...
})

Definindo Cookies

Definição de 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"`
}

Retornando Cookie

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

  // Definir cookie
  c.Cookie(cookie)
  // ...
})

Redirecionar (301 ou 302)

O padrão é um redirecionamento 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)
})