Fiber é inspirado no framework Express, o mais popular da web. Combinamos a usabilidade do Express e o desempenho bruto do Go. Se você já construiu uma aplicação web usando Node.js (usando Express ou um framework similar), muitos métodos e princípios devem ser muito fáceis de entender para você.

Início rápido

Instalação

Certifique-se de ter o Go 1.17 ou superior instalado.

Inicialize seu projeto criando uma pasta e executando go mod init github.com/seu/repo dentro da pasta. Em seguida, instale o Fiber usando o comando go get:

go get -u github.com/gofiber/fiber/v2

Olá, Mundo

package main

// Importe o pacote fiber
import "github.com/gofiber/fiber/v2"

func main() {
    // Defina o aplicativo fiber
    app := fiber.New()

    // Defina a rota http
    app.Get("/", func(c *fiber.Ctx) error {
        // Retorne olá mundo como uma string
        return c.SendString("Olá, Mundo ?!")
    })

    // Ouça na porta 3000
    app.Listen(":3000")
}

Acesse via: http://localhost:3000/

Roteamento Básico

Exemplo básico de roteamento do Fiber

func main() {
    app := fiber.New()

    // GET /api/cadastrar
    app.Get("/api/*", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("✋ %s", c.Params("*"))
        return c.SendString(msg) // => ✋ cadastrar
    })

    // GET /voos/LAX-SFO
    app.Get("/voos/:de-:para", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("? De: %s, Para: %s", c.Params("de"), c.Params("para"))
        return c.SendString(msg) // => ? De: LAX, Para: SFO
    })

    // GET /dicionario.txt
    app.Get("/:arquivo.:extensao", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("? %s.%s", c.Params("arquivo"), c.Params("extensao"))
        return c.SendString(msg) // => ? dicionario.txt
    })

    // GET /john/75
    app.Get("/:nome/:idade/:genero?", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("? %s tem %s anos", c.Params("nome"), c.Params("idade"))
        return c.SendString(msg) // => ? john tem 75 anos
    })

    // GET /john
    app.Get("/:nome", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("Olá, %s ?!", c.Params("nome"))
        return c.SendString(msg) // => Olá john ?!
    })

    log.Fatal(app.Listen(":3000"))
}

Servindo Arquivos Estáticos

Configurando o serviço de arquivos estáticos

func main() {
    app := fiber.New()

    app.Static("/", "./public")
    // => http://localhost:3000/js/script.js
    // => http://localhost:3000/css/style.css

    app.Static("/prefix", "./public")
    // => http://localhost:3000/prefix/js/script.js
    // => http://localhost:3000/prefix/css/style.css

    app.Static("*", "./public/index.html")
    // => http://localhost:3000/qualquer/caminho/mostra/index/html

    log.Fatal(app.Listen(":3000"))
}

Middleware

Aprimore a capacidade de lidar com solicitações HTTP por meio de middlewares.

func main() {
    app := fiber.New()

    // Corresponder a qualquer rota, aqui personalizar o middleware usando uma função de fecho
    app.Use(func(c *fiber.Ctx) error {
        fmt.Println("? Primeiro manipulador")
        // Continue para lidar com o próximo middleware ou função de rota
        return c.Next()
    })

    // Corresponder a rotas que começam com /api
    app.Use("/api", func(c *fiber.Ctx) error {
        fmt.Println("? Segundo manipulador")
        return c.Next()
    })
    
    // Use o middleware integrado para lidar com exceções
    app.Use(recover.New())

    // GET /api/lista
    app.Get("/api/lista", func(c *fiber.Ctx) error {
        fmt.Println("? Último manipulador")
        return c.SendString("Olá, Mundo ?!")
    })

    log.Fatal(app.Listen(":3000"))
}

Motor de Template

Se o motor de template não estiver configurado, o Fiber usará por padrão o html/template.

pacote principal

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/template/pug"
)

func main() {
    // Configurar o motor de template
    app := fiber.New(fiber.Config{
        Views: pug.New("./views", ".pug"),
    })

    app.Get("/", func(c *fiber.Ctx) error {
        // Renderizar o template ./views/home.pug usando os parâmetros do template fiber.map
        return c.Render("home", fiber.Map{
            "title": "Página Inicial",
            "year":  1999,
        })
    })

    log.Fatal(app.Listen(":3000"))
}

Middleware de Compartilhamento de Recursos de Origem Cruzada (CORS)

Middleware para CORS no Fiber, pode habilitar o compartilhamento de recursos de origem cruzada com várias opções para evitar ataques CORS.

import (
    "log"
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/cors"
)

func main() {
    app := fiber.New()

    // Configuração CORS padrão
    app.Use(cors.New())

    // Ou personalizar os parâmetros do CORS para permitir solicitações de determinados domínios
    app.Use(cors.New(cors.Config{
        AllowOrigins: "https://www.tizi365.com, https://tizi365.com",
        AllowHeaders:  "Origin, Content-Type, Accept",
    }))

    log.Fatal(app.Listen(":3000"))
}

Verifique o CORS passando qualquer domínio no cabeçalho Origin:

curl -H "Origin: https://www.tizi365.com" --verbose http://localhost:3000

Resposta 404 Personalizada

func main() {
    app := fiber.New()

    app.Static("/", "./public")

    app.Get("/demo", func(c *fiber.Ctx) error {
        return c.SendString("Isto é uma demonstração!")
    })

    app.Post("/register", func(c *fiber.Ctx) error {
        return c.SendString("Bem-vindo!")
    })

    // O último middleware referenciado corresponderá a todas as solicitações, incluindo 404
    app.Use(func(c *fiber.Ctx) error {
        // Outra lógica de manipulação
        // Retornar status 404
        return c.SendStatus(404)
        // => 404 "Não encontrado"
    })

    log.Fatal(app.Listen(":3000"))
}

Resposta JSON

Exemplo de retorno de dados JSON pelo Fiber.

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    app := fiber.New()

    app.Get("/user", func(c *fiber.Ctx) error {
        return c.JSON(&User{"John", 20})
        // => {"name":"John", "age":20}
    })

    app.Get("/json", func(c *fiber.Ctx) error {
        return c.JSON(fiber.Map{
            "success": true,
            "message": "Olá John!",
        })
        // => {"success":true, "message":"Olá John!"}
    })

    log.Fatal(app.Listen(":3000"))
}

Middleware de Recuperação

Interceptar erros de pânico para evitar a interrupção e saída do programa.

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/recover"
)

func main() {
    app := fiber.New()
	// Usar o middleware de pânico para interceptar exceções de pânico
    app.Use(recover.New())

    app.Get("/", func(c *fiber.Ctx) error {
        panic("normalmente isso iria travar seu aplicativo")
    })

    log.Fatal(app.Listen(":3000"))
}

Benchmark

[

Limitações

  • Devido ao uso de recursos inseguros no Fiber, pode ser incompatível com as últimas versões do Go. O Fiber 2.40.0 foi testado nas versões do Go de 1.17 a 1.21.
  • O Fiber não é compatível com a interface net/http. Isso significa que você não pode usar diretamente projetos como gqlgen, go-swagger, ou qualquer outro projeto pertencente ao ecossistema net/http.