35 KiB
Fiber, Go için en hızlı HTTP motoru olan Fasthttp üzerine inşa edilmiş, Express den ilham alan bir web çatısıdır. Sıfır bellek ayırma ve performans göz önünde bulundurularak hızlı geliştirme için işleri kolaylaştırmak üzere tasarlandı.
⚡️ Hızlı Başlangıç
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)
}
🤖 Performans Ölçümleri
Bu testler TechEmpower ve Go Web ile koşuldu. Bütün sonuçları görmek için lütfen Wiki sayfasını ziyaret ediniz.
⚙️ Kurulum
İlk önce, Go yu indirip kuruyoruz. 1.11
veya daha yeni sürüm gereklidir.
go get
komutunu kullanarak kurulumu tamamlıyoruz:
go get -u github.com/gofiber/fiber/...
🎯 Özellikler
- Güçlü rotalar
- Statik dosya yönetimi
- Olağanüstü performans
- Düşük bellek tüketimi
- API uç noktaları
- Ara katman & Sonraki desteği
- Hızlı sunucu taraflı programlama
- Template engines
- WebSocket support
- Rate Limiter
- Available in 15 languages
- Ve daha fazlası, Fiber ı keşfet
💡 Felsefe
Node.js den Go ya geçen yeni gopher lar kendi web uygulamalarını ve mikroservislerini yazmaya başlamadan önce dili öğrenmek ile uğraşıyorlar. Fiber, bir web çatısı olarak, minimalizm ve UNIX yolunu izlemek fikri ile oluşturuldu. Böylece yeni gopher lar sıcak ve güvenilir bir hoşgeldin ile Go dünyasına giriş yapabilirler.
Fiber internet üzerinde en popüler olan Express web çatısından esinlenmiştir. Biz Express in kolaylığını ve Go nun ham performansını birleştirdik. Daha önce Node.js üzerinde (Express veya benzerini kullanarak) bir web uygulaması geliştirdiyseniz, pek çok metod ve prensip size çok tanıdık gelecektir.
👀 Örnekler
Aşağıda yaygın örneklerden bazıları listelenmiştir. Daha fazla kod örneği görmek için, lütfen Kod deposunu veya API dökümantasyonunu ziyaret ediniz.
Rotalama
📖 Rotalama
func main() {
app := fiber.New()
// GET /john http methodunu çağır
app.Get("/:name", func(c *fiber.Ctx) {
fmt.Printf("Hello %s!", c.Params("name"))
// => Hello john!
})
// GET /john http methodunu çağır
app.Get("/:name/:age?", func(c *fiber.Ctx) {
fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
// => Name: john, Age:
})
// GET /plantae/prunus.persica
app.Get("/plantae/:genus.:species", func(c *fiber.Ctx) {
fmt.Printf("Genius: %s, Species: %s", c.Params("genus"), c.Params("species"))
// => Genius: prunus, Species: persica
})
// GET /flights/LAX-SFO
app.Get("/flights/:from-:to", func(c *fiber.Ctx) {
fmt.Printf("From: %s, To: %s", c.Params("from"), c.Params("to"))
// => From: LAX, To: SFO
})
// GET /api/register http methodunu çağır
app.Get("/api/*", func(c *fiber.Ctx) {
fmt.Printf("/api/%s", c.Params("*"))
// => /api/register
})
app.Listen(3000)
}
Statik Dosyaları Servis Etmek
📖 Statik
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)
}
Ara Katman ve İleri(Middleware & Next)
📖 Ara Katman 📖 İleri
func main() {
app := fiber.New()
// Bütün rotalarla eşleş
app.Use(func(c *fiber.Ctx) {
fmt.Println("First middleware")
c.Next()
})
// /api ile başlayan tüm rotalarla eşleş
app.Use("/api", func(c *fiber.Ctx) {
fmt.Println("Second middleware")
c.Next()
})
// GET /api/register http methodunu çağır
app.Get("/api/list", func(c *fiber.Ctx) {
fmt.Println("Last middleware")
c.Send("Hello, World!")
})
app.Listen(3000)
}
📚 Daha fazla kod örneği göster
Views engines
Fiber defaults to the html/template when no view engine is set.
If you want to execute partials or use a different engine like amber, handlebars, mustache or pug etc..
Checkout our Template package that support multiple view engines.
import (
"github.com/gofiber/fiber"
"github.com/gofiber/template/pug"
)
func main() {
// You can setup Views engine before initiation app:
app := fiber.New(&fiber.Settings{
Views: pug.New("./views", ".pug"),
})
// OR after initiation app at any convenient location:
app.Settings.Views = pug.New("./views", ".pug"),
// And now, you can call template `./views/home.pug` like this:
app.Get("/", func(c *fiber.Ctx) {
c.Render("home", fiber.Map{
"title": "Homepage",
"year": 1999,
})
})
// ...
}
Rotaları Zincirlere Gruplama
📖 Grup
func main() {
app := fiber.New()
// Kök API rotası
api := app.Group("/api", cors()) // /api
// API v1 rotası
v1 := api.Group("/v1", mysql()) // /api/v1
v1.Get("/list", handler) // /api/v1/list
v1.Get("/user", handler) // /api/v1/user
// API v2 rotası
v2 := api.Group("/v2", mongodb()) // /api/v2
v2.Get("/list", handler) // /api/v2/list
v2.Get("/user", handler) // /api/v2/user
// ...
}
Ara Katman Günlükcüsü(Logger)
📖 Günlükcü
import (
"github.com/gofiber/fiber"
"github.com/gofiber/logger"
)
func main() {
app := fiber.New()
// Tercihe bağlı günlük ayarları
config := logger.Config{
Format: "${time} - ${method} ${path}\n",
TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
}
// Günlükcüyü ayarla
app.Use(logger.New(config))
app.Listen(3000)
}
Farklı Merkezler Arası Kaynak Paylaşımı (CORS)
📖 CORS
import (
"github.com/gofiber/fiber"
"github.com/gofiber/cors"
)
func main() {
app := fiber.New()
// Varsayılan ayarlarla CORS
app.Use(cors.New())
app.Listen(3000)
}
Origin
başlığı içinde herhangı bir alan adı kullanarak CORS'u kontrol et:
curl -H "Origin: http://example.com" --verbose http://localhost:3000
Özelleştirilebilir 404 yanıtları
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!")
})
// Herhangi bir şeyle eşleşen son ara katman
app.Use(func(c *fiber.Ctx) {
c.SendStatus(404)
// => 404 "Not Found"
})
app.Listen(3000)
}
JSON Yanıtları
📖 JSON
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 Yükseltmesi
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
📖 Recover
import (
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/middleware"
)
func main() {
app := fiber.New()
app.Use(middleware.Recover())
app.Get("/", func(c *fiber.Ctx) {
panic("normally this would crash your app")
})
app.Listen(3000)
}
🧬 Fiber Middleware
The Fiber middleware modules listed here are maintained by the Fiber team.
Middleware | Description | Built-in middleware |
---|---|---|
adaptor | Converter for net/http handlers to/from Fiber request handlers, special thanks to @arsmn! | - |
basicauth | Basic auth middleware provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized for missing or invalid credentials. | - |
compress | Compression middleware for Fiber, it supports deflate , gzip and brotli by default. |
middleware.Compress() |
cors | Enable cross-origin resource sharing CORS with various options. |
- |
csrf | Protect from CSRF exploits. | - |
embed | FileServer middleware for Fiber, special thanks and credits to Alireza Salary | - |
favicon | Ignore favicon from logs or serve from memory if a file path is provided. | middleware.Favicon() |
helmet | Helps secure your apps by setting various HTTP headers. | - |
jwt | JWT returns a JSON Web Token JWT auth middleware. |
- |
keyauth | Key auth middleware provides a key based authentication. | - |
limiter | Rate-limiting middleware for Fiber. Use to limit repeated requests to public APIs and/or endpoints such as password reset. | - |
logger | HTTP request/response logger. | middleware.Logger() |
pprof | Special thanks to Matthew Lee @mthli |
- |
recover | Recover middleware recovers from panics anywhere in the stack chain and handles the control to the centralized ErrorHandler. | middleware.Recover() |
rewrite | Rewrite middleware rewrites the URL path based on provided rules. It can be helpful for backward compatibility or just creating cleaner and more descriptive links. | - |
requestid | Request ID middleware generates a unique id for a request. | middleware.RequestID() |
session | This session middleware is build on top of fasthttp/session by @savsgio MIT. Special thanks to @thomasvvugt for helping with this middleware. | - |
template | This package contains 8 template engines that can be used with Fiber v1.10.x Go version 1.13 or higher is required. |
- |
websocket | Based on Fasthttp WebSocket for Fiber with Locals support! | - |
🌱 Third Party Middlewares
This is a list of middlewares that are created by the Fiber community, please create a PR if you want to see yours!
- arsmn/fiber-swagger
- arsmn/fiber-casbin
- arsmn/fiber-introspect
- shareed2k/fiber_tracing
- shareed2k/fiber_limiter
- thomasvvugt/fiber-boilerplate
- arsmn/gqlgen
- arsmn/gqlgen
- kiyonlin/fiber_limiter
💬 Medya
- Welcome to Fiber — an Express.js styled web framework written in Go with ❤️ — 03 Feb 2020
- Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly? — 21 Feb 2020
- 🚀 Fiber v1.8. What's new, updated and re-thinked? — 03 Mar 2020
- Is switching from Express to Fiber worth it? 🤔 — 01 Apr 2020
- Creating Fast APIs In Go Using Fiber — 07 Apr 2020
- Building a Basic REST API in Go using Fiber - 23 Apr 2020
- 📺 Building a REST API using GORM and Fiber - 25 Apr 2020
- 🌎 Create a travel list app with Go, Fiber, Angular, MongoDB and Google Cloud Secret Manager - 25 Apr 2020
- Fiber v1.9.6 🔥 How to improve performance by 817% and stay fast, flexible and friendly? - 12 May 2020
- The road to web-based authentication with Fiber ⚡ - 20 May 2020
- Building an Express-style API in Go with Fiber - 10 June 2020
- Construir una API en Golang con Fiber 🇪🇸 - 28 June 2020
- 📺Why Go Fiber Is THE New Framework To Learn - 29 June 2020
👍 Destek
Eğer teşekkür etmek ve/veya Fiber
'in aktif geliştirilmesini desteklemek istiyorsanız:
- Projeye GitHub Yıldızı verin.
- Twitter hesabınızdan proje hakkında tweet atın.
- Medium, Dev.to veya kişisel blog üzerinden bir inceleme veya eğitici yazı yazın.
- API dökümantasyonunu çevirerek destek olabilirsiniz Crowdin
- Projeye [bir fincan kahve] ısmarlayarak projeye destek olabilirsiniz(https://buymeacoff.ee/fenny).
☕ Destekçiler
Fiber, alan adı, gitbook, netlify, serverless yer sağlayıcısı giderleri ve benzeri şeyleri ödemek için bağışlarla yaşayan bir açık kaynaklı projedir. Eğer Fiber'e destek olmak isterseniz, ☕ buradan kahve ısmarlayabilirsiniz.
User | Donation | |
---|---|---|
@destari | ☕ x 10 | |
@thomasvvugt | ☕ x 5 | |
@hendratommy | ☕ x 5 | |
@ekaputra07 | ☕ x 5 | |
@jorgefuertes | ☕ x 5 | |
@candidosales | ☕ x 5 | |
@l0nax | ☕ x 3 | |
@ankush | ☕ x 3 | |
@bihe | ☕ x 3 | |
@justdave | ☕ x 3 | |
@koddr | ☕ x 1 | |
@lapolinar | ☕ x 1 | |
@diegowifi | ☕ x 1 | |
@ssimk0 | ☕ x 1 | |
@raymayemir | ☕ x 1 | |
@melkorm | ☕ x 1 | |
@marvinjwendt | ☕ x 1 | |
@toishy | ☕ x 1 |
💻 Koda Katkı Sağlayanlar
⭐️ Stargazers
⚠️ Lisans
Telif (c) 2019-günümüz Fenny ve Contributors. Fiber
, MIT Lisansı altında özgür ve açık kaynaklı bir yazılımdır. Resmi logosu Vic Shóstak tarafında tasarlanmıştır ve Creative Commons lisansı altında dağıtımı yapılır. (CC BY-SA 4.0 International).
3. Parti yazılım lisanları