Fiber

Fiber é um framework web inspirado no Express, construído sobre o Fasthttp, o motor HTTP mais rápido do Go. Projetado para facilitar e acelerar o desenvolvimento, com zero de alocação de memória e desempenho em mente.

## ⚡️ Início rápido ```go package main import "github.com/gofiber/fiber/v2" func main() { app := fiber.New() app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello, World 👋!") }) app.Listen(":3000") } ``` ## 🤖 Benchmarks Esses testes são realizados pelo [TechEmpower](https://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=plaintext) e [Go Web](https://github.com/smallnest/go-web-framework-benchmark). Se você quiser ver todos os resultados, visite nosso [Wiki](https://docs.gofiber.io/extra/benchmarks) .

## ⚙️ Instalação Certifique-se de ter o Go instalado ([download](https://go.dev/dl/)). Versão `1.17` ou superior é obrigatória. Inicie seu projeto criando um diretório e então execute `go mod init github.com/your/repo` ([saiba mais](https://go.dev/blog/using-go-modules)) dentro dele. Então, instale o Fiber com o comando [`go get`](https://pkg.go.dev/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them): ```bash go get -u github.com/gofiber/fiber/v2 ``` ## 🎯 Recursos - [Roteamento](https://docs.gofiber.io/guide/routing) robusto - Servir [arquivos estáticos](https://docs.gofiber.io/api/app#static) - [Desempenho](https://docs.gofiber.io/extra/benchmarks) extremo - [Baixo consumo de memória](https://docs.gofiber.io/extra/benchmarks) - [API de rotas](https://docs.gofiber.io/api/ctx) - Suporte à Middleware e [Next](https://docs.gofiber.io/api/ctx#next) - Programação [rápida](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) de aplicações de servidor - [Templates](https://github.com/gofiber/template) - [Suporte à WebSockets](https://github.com/gofiber/websocket) - [Server-Sent events](https://github.com/gofiber/recipes/tree/master/sse) - [Limitador de requisições](https://docs.gofiber.io/api/middleware/limiter) - Disponível em [19 línguas](https://docs.gofiber.io/) - E muito mais, [explore o Fiber](https://docs.gofiber.io/) ## 💡 Filosofia Os novos gophers que mudaram do [Node.js](https://nodejs.org/en/about/) para o [Go](https://go.dev/doc/) estão tendo que lidar com uma curva de aprendizado antes que possam começar a criar seus aplicativos web ou microsserviços. O Fiber, como um **framework web**, foi criado com a ideia de ser **minimalista** e seguindo a **filosofia UNIX**, para que novos gophers possam, rapidamente, entrar no mundo do Go com uma recepção calorosa e confiável. O Fiber é **inspirado** no Express, o framework web mais popular da Internet. Combinamos a **facilidade** do Express e com o **desempenho bruto** do Go. Se você já implementou um aplicativo web com Node.js ( _usando Express.js ou similar_ ), então muitos métodos e princípios parecerão **muito familiares** para você. ## ⚠️ Limitações - Devido ao uso de "unsafe" pelo Fiber, a biblioteca pode nem sempre ser compatível com a última versão do Go. Fiber 2.40.0 foi testado com as versões Go de 1.17 a 1.21. - Fiber não é compatível com as interfaces net/http. Isso significa que você não poderá usar projetos como gqlgen, go-swagger ou quaisquer outros que fazem parte do ecossistema net/http. ## 👀 Exemplos Listados abaixo estão alguns exemplos comuns. Se você quiser ver mais exemplos de código, visite nosso [repositório de receitas](https://github.com/gofiber/recipes) ou a [documentação da API](https://docs.gofiber.io). #### 📖 [**Roteamento básico**](https://docs.gofiber.io/#basic-routing) ```go func main() { app := fiber.New() // GET /api/register app.Get("/api/*", func(c *fiber.Ctx) error { msg := fmt.Sprintf("✋ %s", c.Params("*")) return c.SendString(msg) // => ✋ register }) // GET /flights/LAX-SFO app.Get("/flights/:from-:to", func(c *fiber.Ctx) error { msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to")) return c.SendString(msg) // => 💸 From: LAX, To: SFO }) // GET /dictionary.txt app.Get("/:file.:ext", func(c *fiber.Ctx) error { msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext")) return c.SendString(msg) // => 📃 dictionary.txt }) // GET /john/75 app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error { msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age")) return c.SendString(msg) // => 👴 john is 75 years old }) // GET /john app.Get("/:name", func(c *fiber.Ctx) error { msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name")) return c.SendString(msg) // => Hello john 👋! }) log.Fatal(app.Listen(":3000")) } ``` #### 📖 [**Nome de Rotas**](https://docs.gofiber.io/api/app#name) ```go func main() { app := fiber.New() // GET /api/register app.Get("/api/*", func(c *fiber.Ctx) error { msg := fmt.Sprintf("✋ %s", c.Params("*")) return c.SendString(msg) // => ✋ register }).Name("api") data, _ := json.MarshalIndent(app.GetRoute("api"), "", " ") fmt.Print(string(data)) // Prints: // { // "method": "GET", // "name": "api", // "path": "/api/*", // "params": [ // "*1" // ] // } log.Fatal(app.Listen(":3000")) } ``` #### 📖 [**Servindo arquivos estáticos**](https://docs.gofiber.io/api/app#static) ```go 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/any/path/shows/index/html log.Fatal(app.Listen(":3000")) } ``` #### 📖 [**Middleware & Next**](https://docs.gofiber.io/api/ctx#next) ```go func main() { app := fiber.New() // Match any route app.Use(func(c *fiber.Ctx) error { fmt.Println("🥇 First handler") return c.Next() }) // Match all routes starting with /api app.Use("/api", func(c *fiber.Ctx) error { fmt.Println("🥈 Second handler") return c.Next() }) // GET /api/register app.Get("/api/list", func(c *fiber.Ctx) error { fmt.Println("🥉 Last handler") return c.SendString("Hello, World 👋!") }) log.Fatal(app.Listen(":3000")) } ```
📚 Mostrar mais exemplos ### Engines de visualização 📖 [Config](https://docs.gofiber.io/api/fiber#config) 📖 [Engines](https://github.com/gofiber/template) 📖 [Render](https://docs.gofiber.io/api/ctx#render) O Fiber usa por padrão o [html/template](https://pkg.go.dev/html/template/) quando nenhuma engine é selecionada. Se você quiser uma execução parcial ou usar uma engine diferente como [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) ou [pug](https://github.com/Joker/jade) etc.. Dê uma olhada no package [Template](https://github.com/gofiber/template) que suporta multiplas engines de visualização. ```go package main import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/template/pug" ) func main() { // You can setup Views engine before initiation app: app := fiber.New(fiber.Config{ Views: pug.New("./views", ".pug"), }) // And now, you can call template `./views/home.pug` like this: app.Get("/", func(c *fiber.Ctx) error { return c.Render("home", fiber.Map{ "title": "Homepage", "year": 1999, }) }) log.Fatal(app.Listen(":3000")) } ``` ### Agrupamento de rotas 📖 [Group](https://docs.gofiber.io/api/app#group) ```go func middleware(c *fiber.Ctx) error { fmt.Println("Don't mind me!") return c.Next() } func handler(c *fiber.Ctx) error { return c.SendString(c.Path()) } func main() { app := fiber.New() // Root API route api := app.Group("/api", middleware) // /api // API v1 routes v1 := api.Group("/v1", middleware) // /api/v1 v1.Get("/list", handler) // /api/v1/list v1.Get("/user", handler) // /api/v1/user // API v2 routes v2 := api.Group("/v2", middleware) // /api/v2 v2.Get("/list", handler) // /api/v2/list v2.Get("/user", handler) // /api/v2/user // ... } ``` ### Middleware Logger 📖 [Logger](https://docs.gofiber.io/api/middleware/logger) ```go package main import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" ) func main() { app := fiber.New() app.Use(logger.New()) // ... log.Fatal(app.Listen(":3000")) } ``` ### Cross-Origin Resource Sharing (CORS) 📖 [CORS](https://docs.gofiber.io/api/middleware/cors) ```go import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" ) func main() { app := fiber.New() app.Use(cors.New()) // ... log.Fatal(app.Listen(":3000")) } ``` Verifique o CORS passando qualquer domínio no header `Origin`: ```bash curl -H "Origin: http://example.com" --verbose http://localhost:3000 ``` ### Resposta 404 customizada 📖 [HTTP Methods](https://docs.gofiber.io/api/ctx#status) ```go func main() { app := fiber.New() app.Static("/", "./public") app.Get("/demo", func(c *fiber.Ctx) error { return c.SendString("This is a demo!") }) app.Post("/register", func(c *fiber.Ctx) error { return c.SendString("Welcome!") }) // Last middleware to match anything app.Use(func(c *fiber.Ctx) error { return c.SendStatus(404) // => 404 "Not Found" }) log.Fatal(app.Listen(":3000")) } ``` ### Resposta JSON 📖 [JSON](https://docs.gofiber.io/api/ctx#json) ```go 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": "Hi John!", }) // => {"success":true, "message":"Hi John!"} }) log.Fatal(app.Listen(":3000")) } ``` ### WebSocket 📖 [Websocket](https://github.com/gofiber/websocket) ```go import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/websocket" ) func main() { app := fiber.New() app.Get("/ws", websocket.New(func(c *websocket.Conn) { for { mt, msg, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", msg) err = c.WriteMessage(mt, msg) if err != nil { log.Println("write:", err) break } } })) log.Fatal(app.Listen(":3000")) // ws://localhost:3000/ws } ``` ### Server-Sent Events 📖 [More Info](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) ```go import ( "github.com/gofiber/fiber/v2" "github.com/valyala/fasthttp" ) func main() { app := fiber.New() app.Get("/sse", func(c *fiber.Ctx) error { c.Set("Content-Type", "text/event-stream") c.Set("Cache-Control", "no-cache") c.Set("Connection", "keep-alive") c.Set("Transfer-Encoding", "chunked") c.Context().SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) { fmt.Println("WRITER") var i int for { i++ msg := fmt.Sprintf("%d - the time is %v", i, time.Now()) fmt.Fprintf(w, "data: Message: %s\n\n", msg) fmt.Println(msg) w.Flush() time.Sleep(5 * time.Second) } })) return nil }) log.Fatal(app.Listen(":3000")) } ``` ### Middleware Recover 📖 [Recover](https://docs.gofiber.io/api/middleware/recover) ```go import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/recover" ) func main() { app := fiber.New() app.Use(recover.New()) app.Get("/", func(c *fiber.Ctx) error { panic("normally this would crash your app") }) log.Fatal(app.Listen(":3000")) } ```
## 🧬 Middleware Interno Aqui está uma lista de middlewares que estão incluídos no framework Fiber. | Middleware | Descrição | | :------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [basicauth](https://github.com/gofiber/fiber/tree/master/middleware/basicauth) | Autenticação básica fornece uma autenticação HTTP básica. Ele chama o próximo manipulador para credenciais válidas e 401 Não Autorizado para credenciais ausentes ou inválidas. | | [cache](https://github.com/gofiber/fiber/tree/master/middleware/cache) | Intercepta e armazena em cache as respostas | | [compress](https://github.com/gofiber/fiber/tree/master/middleware/compress) | Middleware de compressão para o Fiber, suporta `deflate`, `gzip` e `brotli` por padrão. | | [cors](https://github.com/gofiber/fiber/tree/master/middleware/cors) | Habilita o compartilhamento de recursos de origem cruzada (CORS) com várias opções. | | [csrf](https://github.com/gofiber/fiber/tree/master/middleware/csrf) | Protege contra exploits CSRF. | | [encryptcookie](https://github.com/gofiber/fiber/tree/master/middleware/encryptcookie) | Criptografa valores de cookie. | | [envvar](https://github.com/gofiber/fiber/tree/master/middleware/envvar) | Expõe variáveis de ambiente fornecendo uma configuração opcional. | | [etag](https://github.com/gofiber/fiber/tree/master/middleware/etag) | Permite que caches sejam mais eficientes e economizem largura de banda, pois um servidor web não precisa reenviar uma resposta completa se o conteúdo não mudou. | | [expvar](https://github.com/gofiber/fiber/tree/master/middleware/expvar) | Serve via seu servidor HTTP variantes expostas em tempo de execução no formato JSON. | | [favicon](https://github.com/gofiber/fiber/tree/master/middleware/favicon) | Ignora favicon dos logs ou serve da memória se um caminho de arquivo for fornecido. | | [filesystem](https://github.com/gofiber/fiber/tree/master/middleware/filesystem) | Sistema de Arquivos para o Fiber, agradecimentos especiais e créditos a Alireza Salary | | [limiter](https://github.com/gofiber/fiber/tree/master/middleware/limiter) | Limitação de taxa para o Fiber. Use para limitar solicitações repetidas para APIs públicas e/ou endpoints como redefinição de senha. | | [logger](https://github.com/gofiber/fiber/tree/master/middleware/logger) | Logger de solicitação/resposta HTTP. | | [monitor](https://github.com/gofiber/fiber/tree/master/middleware/monitor) | Middleware de monitoramento que relata métricas do servidor, inspirado pelo express-status-monitor | | [pprof](https://github.com/gofiber/fiber/tree/master/middleware/pprof) | Agradecimentos especiais a Matthew Lee (@mthli) | | [proxy](https://github.com/gofiber/fiber/tree/master/middleware/proxy) | Permite que você faça proxy de solicitações a vários servidores | | [recover](https://github.com/gofiber/fiber/tree/master/middleware/recover) | Recupera de panics em qualquer lugar da cadeia de chamadas e passa o controle para o [ErrorHandler](https://docs.gofiber.io/guide/error-handling) centralizado. | | [requestid](https://github.com/gofiber/fiber/tree/master/middleware/requestid) | Adiciona um ID de solicitação a cada pedido. | | [session](https://github.com/gofiber/fiber/tree/master/middleware/session) | Middleware de sessão. NOTA: Este middleware usa nosso pacote Storage. | | [skip](https://github.com/gofiber/fiber/tree/master/middleware/skip) | Pula um handler envolto se um predicado for verdadeiro. | | [timeout](https://github.com/gofiber/fiber/tree/master/middleware/timeout) | Adiciona um tempo máximo para uma solicitação e encaminha para ErrorHandler se ele for excedido. | | [keyauth](https://github.com/gofiber/keyauth) | Autenticação por chave fornece uma autenticação baseada em chave. | | [redirect](https://github.com/gofiber/redirect) | Middleware de redirecionamento | | [rewrite](https://github.com/gofiber/rewrite) | Reescreve o caminho da URL com base nas regras fornecidas. Pode ser útil para compatibilidade retroativa ou para criar links mais limpos e descritivos. | | [adaptor](https://github.com/gofiber/adaptor) | Conversor para handlers net/http para/para manipuladores de solicitação Fiber, agradecimentos especiais ao @arsmn! | | [helmet](https://github.com/gofiber/helmet) | Ajuda a proteger seus aplicativos definindo vários cabeçalhos HTTP. | ## 🧬 Middleware Externo Lista de módulos de middleware hospedados externamente e mantidos pela [equipe Fiber](https://github.com/orgs/gofiber/people). | Middleware | Descrição | | :------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------- | | [jwt](https://github.com/gofiber/jwt) | JWT retorna um middleware de autenticação com tokens JWT. | | [storage](https://github.com/gofiber/storage) | Drivers de armazenamento prontos que implementam a interface Storage, projetados para serem usados com vários middlewares do Fiber. | | [template](https://github.com/gofiber/template) | Este pacote contém 8 mecanismos de template que podem ser usados com Fiber `v1.10.x`. É necessário Go versão 1.13 ou superior. | | [websocket](https://github.com/gofiber/websocket) | Baseado no WebSocket do Fasthttp para Fiber com suporte a Locals | ## 🕶️ Lista Incrível Para mais artigos, middlewares, exemplos ou ferramentas, confira nossa [lista incrível](https://github.com/gofiber/awesome-fiber). ## 👍 Contribuindo Se você quer **agradecer** e/ou apoiar o desenvolvimento ativo do `Fiber`: 1. Deixe uma [estrela no GitHub](https://github.com/gofiber/fiber/stargazers) do projeto. 2. Tweet sobre o projeto [no seu Twitter](https://twitter.com/intent/tweet?text=Fiber%20is%20an%20Express%20inspired%20%23web%20%23framework%20built%20on%20top%20of%20Fasthttp%2C%20the%20fastest%20HTTP%20engine%20for%20%23Go.%20Designed%20to%20ease%20things%20up%20for%20%23fast%20development%20with%20zero%20memory%20allocation%20and%20%23performance%20in%20mind%20%F0%9F%9A%80%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber). 3. Escreva um review ou tutorial no [Medium](https://medium.com/), [Dev.to](https://dev.to/) ou blog pessoal. 4. Apoie o projeto pagando uma [xícara de café](https://buymeacoff.ee/fenny). ## ☕ Apoiadores Fiber é um projeto open source que usa de doações para pagar seus custos (domínio, GitBook, Netlify e hospedagem serverless). Se você quiser apoiar o projeto, você pode ☕ [**pagar um café**](https://buymeacoff.ee/fenny). | | User | Donation | | :--------------------------------------------------------- | :----------------------------------------------- | :------- | | ![](https://avatars.githubusercontent.com/u/204341?s=25) | [@destari](https://github.com/destari) | ☕ x 10 | | ![](https://avatars.githubusercontent.com/u/63164982?s=25) | [@dembygenesis](https://github.com/dembygenesis) | ☕ x 5 | | ![](https://avatars.githubusercontent.com/u/56607882?s=25) | [@thomasvvugt](https://github.com/thomasvvugt) | ☕ x 5 | | ![](https://avatars.githubusercontent.com/u/27820675?s=25) | [@hendratommy](https://github.com/hendratommy) | ☕ x 5 | | ![](https://avatars.githubusercontent.com/u/1094221?s=25) | [@ekaputra07](https://github.com/ekaputra07) | ☕ x 5 | | ![](https://avatars.githubusercontent.com/u/194590?s=25) | [@jorgefuertes](https://github.com/jorgefuertes) | ☕ x 5 | | ![](https://avatars.githubusercontent.com/u/186637?s=25) | [@candidosales](https://github.com/candidosales) | ☕ x 5 | | ![](https://avatars.githubusercontent.com/u/29659953?s=25) | [@l0nax](https://github.com/l0nax) | ☕ x 3 | | ![](https://avatars.githubusercontent.com/u/635852?s=25) | [@bihe](https://github.com/bihe) | ☕ x 3 | | ![](https://avatars.githubusercontent.com/u/307334?s=25) | [@justdave](https://github.com/justdave) | ☕ x 3 | | ![](https://avatars.githubusercontent.com/u/11155743?s=25) | [@koddr](https://github.com/koddr) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/29042462?s=25) | [@lapolinar](https://github.com/lapolinar) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/2978730?s=25) | [@diegowifi](https://github.com/diegowifi) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/44171355?s=25) | [@ssimk0](https://github.com/ssimk0) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/5638101?s=25) | [@raymayemir](https://github.com/raymayemir) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/619996?s=25) | [@melkorm](https://github.com/melkorm) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/31022056?s=25) | [@marvinjwendt](https://github.com/thomasvvugt) | ☕ x 1 | | ![](https://avatars.githubusercontent.com/u/31921460?s=25) | [@toishy](https://github.com/toishy) | ☕ x 1 | ## ‎‍💻 Contribuidores de código Code Contributors ## ⭐️ Stargazers Stargazers over time ## ⚠️ Licença Todos os direitos reservados (c) 2019-presente [Fenny](https://github.com/fenny) e [Contribuidores](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` é software livre e aberto sob a [licença MIT](https://github.com/gofiber/fiber/blob/master/LICENSE). O logo oficial foi criado por [Vic Shóstak](https://github.com/koddr) e distribuído sob a licença [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) (CC BY-SA 4.0 International). **Licença das bibliotecas de terceiros** - [colorable](https://github.com/mattn/go-colorable/blob/master/LICENSE) - [isatty](https://github.com/mattn/go-isatty/blob/master/LICENSE) - [runewidth](https://github.com/mattn/go-runewidth/blob/master/LICENSE) - [fasthttp](https://github.com/valyala/fasthttp/blob/master/LICENSE) - [bytebufferpool](https://github.com/valyala/bytebufferpool/blob/master/LICENSE) - [fwd](https://github.com/philhofer/fwd/blob/master/LICENSE.md) - [go-ole](https://github.com/go-ole/go-ole/blob/master/LICENSE) - [gopsutil](https://github.com/shirou/gopsutil/blob/master/LICENSE) - [msgp](https://github.com/tinylib/msgp/blob/master/LICENSE) - [schema](https://github.com/gorilla/schema/blob/master/LICENSE) - [uuid](https://github.com/google/uuid/blob/master/LICENSE) - [wmi](https://github.com/StackExchange/wmi/blob/master/LICENSE)