Este capítulo presenta cómo Go Fiber maneja las solicitudes y respuestas, típicamente devolviendo datos JSON para el desarrollo actual de la API.
El framework Fiber utiliza principalmente los datos de retorno del objeto de contexto Ctx.
Devolución de datos en formato JSON
type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c *fiber.Ctx) error {
// Crear estructura de datos para la respuesta
data := SomeStruct{
Name: "Grame",
Age: 20,
}
// Devolver usando la función 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}"
})
Devolución de datos en formato JSONP
type SomeStruct struct {
name string
age uint8
}
app.Get("/", func(c *fiber.Ctx) error {
// Crear estructura de datos
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})
})
Devolución de texto
app.Get("/", func(c *fiber.Ctx) error {
// Devolver "¡Hola, mundo!" como una cadena de texto
return c.SendString("¡Hola, mundo!")
})
Devolución de código de estado
app.Get("/not-found", func(c *fiber.Ctx) error {
// Establecer el código de estado de la respuesta
return c.SendStatus(415)
// => 415 "Tipo de medio no compatible"
c.SendString("¡Hola, mundo!")
// Establecer el código de estado de la respuesta
return c.SendStatus(415)
// => 415 "¡Hola, mundo!"
})
Devolución de archivos (Implementar descarga de archivos)
app.Get("/", func(c *fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => Descargar report-12345.pdf
return c.Download("./files/report-12345.pdf", "report.pdf");
// => Descargar report.pdf
})
Configuración de encabezados de solicitud
app.Get("/", func(c *fiber.Ctx) error {
c.Set("Content-Type", "text/plain")
// => "Content-Type: text/plain"
// ...
})
Configuración de cookies
Definición 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"`
}
Devolver cookie
app.Get("/", func(c *fiber.Ctx) error {
// Crear cookie
cookie := new(fiber.Cookie)
cookie.Name = "john"
cookie.Value = "doe"
cookie.Expires = time.Now().Add(24 * time.Hour)
// Establecer cookie
c.Cookie(cookie)
// ...
})
Redireccionamiento (301 o 302)
El redireccionamiento predeterminado es 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)
})