Fiber


Fiber — это веб фреймворк, который был вдохновлен Express и основан на Fasthttp, самом быстром HTTP-движке написанном на Go. Фреймворк был разработан с целью упростить процесс быстрой разработки высокопроизводительных веб-приложений с нулевым распределением памяти.

## ⚡️ Быстрый старт ```go package main import "github.com/gofiber/fiber" func main() { app := fiber.New() app.Get("/", func(c *fiber.Ctx) { c.Send("Hello, World!") }) app.Listen(3000) } ``` ## ⚙️ Установка Прежде всего, [скачайте](https://golang.org/dl/) и установите Go. Версия **1.11** или выше. Установка выполняется с помощью команды [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them): ```bash go get -u github.com/gofiber/fiber ``` ## 🤖 Бенчмарки Тестирование проводилось с помощью [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) и [Go Web](https://github.com/smallnest/go-web-framework-benchmark). Если вы хотите увидеть все результаты, пожалуйста, посетите наш [Wiki](https://fiber.wiki/benchmarks).

## 🎯 Особенности - Надежная [маршрутизация](https://fiber.wiki/routing) - Доступ к [статичным файлам](https://fiber.wiki/application#static) - Экстремальная [производительность](https://fiber.wiki/benchmarks) - [Низкий объем потребления памяти](https://fiber.wiki/benchmarks) - [Эндпоинты](https://fiber.wiki/context), как в [API](https://fiber.wiki/context) Express - [Middleware](https://fiber.wiki/middleware) и поддержка [Next](https://fiber.wiki/context#next) - [Быстрое](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) программирование на стороне сервера - Переведен на 9 других языков - И многое другое, [посетите наш Wiki](https://fiber.wiki/) ## 💡 Философия Новые Go-программисты, которые переключаются с [Node.js](https://nodejs.org/en/about/) на [Go](https://golang.org/doc/), имеют дело с очень извилистой кривой обучения, прежде чем они смогут начать создавать свои веб-приложения или микросервисы. Fiber, как **веб-фреймворк**, был создан с идеей **минимализма** и следовал **принципу UNIX**, так что новички смогут быстро войти в мир Go без особых проблем. Fiber **вдохновлен** Express, самым популярным веб фреймворком в Интернете. Мы объединили **простоту** Express и **чистую производительность** Go. Если вы когда-либо реализовывали веб-приложение на Node.js (*с использованием Express или аналогичного фреймворка*), то многие методы и принципы покажутся вам **очень знакомыми**. Мы **прислушиваемся** к нашим пользователям в [issues](https://github.com/gofiber/fiber/issues) (_и остальном Интернете_), чтобы создать **быстрый**, **гибкий** и **дружелюбный** веб фреймворк на Go для **любых** задач, **дедлайнов** и **уровней** разработчиков! Как это делает Express в мире JavaScript. ## 👀 Примеры Ниже перечислены некоторые из распространенных примеров. Если вы хотите увидеть больше примеров кода, пожалуйста, посетите наш [репозиторий рецептов](https://github.com/gofiber/recipes) или [документацию по API](https://fiber.wiki). ### Роутинг Документация: - 📖 https://fiber.wiki/#basic-routing Пример: ```go func main() { app := fiber.New() // GET /john app.Get("/:name", func(c *fiber.Ctx) { fmt.Printf("Hello %s!", c.Params("name")) // => Hello john! }) // GET /john app.Get("/:name/:age?", func(c *fiber.Ctx) { fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age")) // => Name: john, Age: }) // GET /api/register app.Get("/api*", func(c *fiber.Ctx) { fmt.Printf("/api%s", c.Params("*")) // => /api/register }) app.Listen(3000) } ``` ### Обслуживание статичных файлов Документация: - 📖 https://fiber.wiki/application#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 app.Listen(3000) } ``` ### Middleware и функция Next Документация: - 📖 https://fiber.wiki/routing#middleware - 📖 https://fiber.wiki/context#next Пример: ```go func main() { app := fiber.New() // Match any route app.Use(func(c *fiber.Ctx) { fmt.Println("First middleware") c.Next() }) // Match all routes starting with /api app.Use("/api", func(c *fiber.Ctx) { fmt.Println("Second middleware") c.Next() }) // POST /api/register app.Post("/api/register", func(c *fiber.Ctx) { fmt.Println("Last middleware") c.Send("Hello, World!") }) app.Listen(3000) } ```
📚 Show more code examples ### Template engines Docs: - 📖 https://fiber.wiki/application#settings - 📖 https://fiber.wiki/context#render Supported engines: - [html](https://golang.org/pkg/html/template/) - [amber](https://github.com/eknkc/amber) - [handlebars](https://github.com/aymerick/raymond) - [mustache](https://github.com/cbroglie/mustache) - [pug](https://github.com/Joker/jade) Example: ```go func main() { // You can setup template engine before initiation app: app := fiber.New(&fiber.Settings{ TemplateEngine: "mustache", TemplateFolder: "./views", TemplateExtension: ".tmpl", }) // OR after initiation app at any convenient location: app.Settings.TemplateEngine = "mustache" app.Settings.TemplateFolder = "./views" app.Settings.TemplateExtension = ".tmpl" // And now, you can call template `./views/home.tmpl` like this: app.Get("/", func(c *fiber.Ctx) { c.Render("home", fiber.Map{ "title": "Homepage", "year": 1999, }) }) // ... } ``` ### Grouping routes into chains Docs: - 📖 https://fiber.wiki/application#group Example: ```go func main() { app := fiber.New() // Root API route api := app.Group("/api", cors()) // /api // API v1 routes v1 := api.Group("/v1", mysql()) // /api/v1 v1.Get("/list", handler) // /api/v1/list v1.Get("/user", handler) // /api/v1/user // API v2 routes v2 := api.Group("/v2", mongodb()) // /api/v2 v2.Get("/list", handler) // /api/v2/list v2.Get("/user", handler) // /api/v2/user // ... } ``` ### Middleware logger Docs: - 📖 https://fiber.wiki/middleware#logger Example: ```go import ( "github.com/gofiber/fiber" "github.com/gofiber/logger" ) func main() { app := fiber.New() // Optional logger config config := logger.LoggerConfig{ Format: "${time} - ${method} ${path}\n", TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST", } // Logger with config app.Use(logger.New(config)) app.Listen(3000) } ``` ### Cross-Origin Resource Sharing (CORS) Docs: - 📖 https://fiber.wiki/middleware#cors Example: ```go import ( "github.com/gofiber/fiber" "github.com/gofiber/cors" ) func main() { app := fiber.New() // CORS with default config app.Use(cors.New()) app.Listen(3000) } ``` Check CORS by passing any domain in `Origin` header: ```bash curl -H "Origin: http://example.com" --verbose http://localhost:3000 ``` ### Custom 404 response Docs: - 📖 https://fiber.wiki/application#http-methods Example: ```go func main() { app := fiber.New() app.Static("/public") app.Get("/demo", func(c *fiber.Ctx) { c.Send("This is a demo!") }) app.Post("/register", func(c *fiber.Ctx) { c.Send("Welcome!") }) // Last middleware to match anything app.Use(func(c *fiber.Ctx) { c.SendStatus(404) // => 404 "Not Found" }) app.Listen(3000) } ``` ### JSON Response Docs: - 📖 https://fiber.wiki/context#json Example: ```go type User struct { Name string `json:"name"` Age int `json:"age"` } func main() { app := fiber.New() app.Get("/user", func(c *fiber.Ctx) { c.JSON(&User{"John", 20}) // => {"name":"John", "age":20} }) app.Get("/json", func(c *fiber.Ctx) { c.JSON(fiber.Map{ "success": true, "message": "Hi John!", }) // => {"success":true, "message":"Hi John!"} }) app.Listen(3000) } ``` ### WebSocket middleware Docs: - 📖 https://fiber.wiki/middleware#websocket Example: ```go import ( "github.com/gofiber/fiber" "github.com/gofiber/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 } } })) app.Listen(3000) // ws://localhost:3000/ws } ``` ### Recover middleware Docs: - 📖 https://fiber.wiki/middleware#recover Example: ```go import ( "github.com/gofiber/fiber" "github.com/gofiber/recover" ) func main() { app := fiber.New() // Optional recover config config := recover.LoggerConfig{ Handler: func(c *fiber.Ctx, err error) { c.SendString(err.Error()) c.SendStatus(500) }, } // Logger with custom config app.Use(recover.New(config)) app.Listen(3000) } ```
## 🧬 Доступные Middleware Для более простой и прозрачной работы, мы вынесли [middleware](https://fiber.wiki/middleware) в отдельные репозитории: - [Basic Authentication](https://github.com/gofiber/basicauth) - [Key Authentication](https://github.com/gofiber/keyauth) - [Compression](https://github.com/gofiber/compression) - [Request ID](https://github.com/gofiber/requestid) - [WebSocket](https://github.com/gofiber/websocket) - [Rewrite](https://github.com/gofiber/rewrite) - [Recover](https://github.com/gofiber/recover) - [Limiter](https://github.com/gofiber/limiter) - [Session](https://github.com/gofiber/session) - [Logger](https://github.com/gofiber/logger) - [Helmet](https://github.com/gofiber/helmet) - [CORS](https://github.com/gofiber/cors) - [CSRF](https://github.com/gofiber/csrf) - [JWT](https://github.com/gofiber/jwt) ## 💬 Медиа - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) (_by [Vic Shóstak](https://github.com/koddr), 03 Feb 2020_) - [Fiber release v1.7 is out now! 🎉 What's new and is he still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) (_by [Vic Shóstak](https://github.com/koddr), 21 Feb 2020_) - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) (_by [Vic Shóstak](https://github.com/koddr), 03 Mar 2020_) ## 👍 Помощь проекту Если вы хотите сказать **спасибо** и/или поддержать активное развитие `Fiber`: 1. Добавьте [GitHub Star](https://github.com/gofiber/fiber/stargazers) в проект. 2. Напишите о проекте [в вашем Twitter](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber). 3. Сделайте обзор фреймворка на [Medium](https://medium.com/), [Dev.to](https://dev.to/) или в личном блоге. 4. Помогите нам перевести `README` и [API](https://fiber.wiki/) на другой язык. ## ☕ Те, кто уже поддержал проект Buy Me A Coffee

HenrikBinggl

Vic Shóstak

MarvinJWendt

ToishY

JustDave
## ⭐️ Звезды Stars over time ## ⚠️ Лицензия `Fiber` — это бесплатное программное обеспечение с открытым исходным кодом, лицензированное по [лицензии MIT](https://github.com/gofiber/fiber/blob/master/LICENSE). Официальный логотип был создан [Vic Shóstak](https://github.com/koddr) и распространяется по лицензии [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) (CC BY-SA 4.0 International).
[![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/0)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/0) [![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/1)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/1) [![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/2)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/2) [![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/3)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/3) [![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/4)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/4) [![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/5)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/5) [![](https://sourcerer.io/fame/Fenny/gofiber/fiber/images/6)](https://sourcerer.io/fame/Fenny/gofiber/fiber/links/6)