Ce chapitre présente comment Go Fiber gère les requêtes et les réponses, en retournant généralement des données JSON pour le développement actuel de l'API.

Le framework Fiber utilise principalement les données renvoyées par l'objet de contexte Ctx.

Retourner des données JSON

type SomeStruct struct {
  Name string
  Age  uint8
}

app.Get("/json", func(c *fiber.Ctx) error {
  // Créer une structure de données pour la réponse
  data := SomeStruct{
    Name: "Grame",
    Age:  20,
  }

  // Renvoyer en utilisant la fonction 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}"
})

Retourner au format JSONP

type SomeStruct struct {
  name string
  age  uint8
}

app.Get("/", func(c *fiber.Ctx) error {
  // Créer une structure de données
  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})
})

Retourner un texte

app.Get("/", func(c *fiber.Ctx) error {
        // Renvoyer "Hello, World ?!" en tant que chaîne de caractères
        return c.SendString("Hello, World ?!")
})

Retourner un code d'état

app.Get("/not-found", func(c *fiber.Ctx) error {
  // Définir le code d'état de la réponse
  return c.SendStatus(415)
  // => 415 "Unsupported Media Type"

  c.SendString("Hello, World!")
  // Définir le code d'état de la réponse
  return c.SendStatus(415)
  // => 415 "Hello, World!"
})

Retourner des fichiers (Implémenter le téléchargement de fichiers)

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

  return c.Download("./files/report-12345.pdf", "report.pdf");
  // => Télécharger report.pdf
})

Définition des en-têtes de requête

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

  // ...
})

Définition des cookies

Définition du 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"`
}

Renvoyer un cookie

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

  // Définir le cookie
  c.Cookie(cookie)
  // ...
})

Redirection (301 ou 302)

La valeur par défaut est une redirection 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)
})