1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-23 16:23:58 +00:00
fiber/.github/README_tr.md
2020-07-01 10:44:15 +02:00

35 KiB
Raw Blame History

Fiber

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

💡 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.

📖 Basic Routing

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

  // GET /john
  app.Get("/:name", func(c *fiber.Ctx) {
    msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
    c.Send(msg) // => Hello john 👋!
  })

  // GET /john/75
  app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) {
    msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
    c.Send(msg) // => 👴 john is 75 years old
  })

  // GET /dictionary.txt
  app.Get("/:file.:ext", func(c *fiber.Ctx) {
    msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
    c.Send(msg) // => 📃 dictionary.txt
  })

  // GET /flights/LAX-SFO
  app.Get("/flights/:from-:to", func(c *fiber.Ctx) {
    msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
    c.Send(msg) // => 💸 From: LAX, To: SFO
  })

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

  app.Listen(3000)
}

📖 Serving Static Files

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

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

  // Match any route
  app.Use(func(c *fiber.Ctx) {
    fmt.Println("🥇 First handler")
    c.Next()
  })

  // Match all routes starting with /api
  app.Use("/api", func(c *fiber.Ctx) {
    fmt.Println("🥈 Second handler")
    c.Next()
  })

  // GET /api/register
  app.Get("/api/list", func(c *fiber.Ctx) {
    fmt.Println("🥉 Last handler")
    c.Send("Hello, World 👋!")
  })

  app.Listen(3000)
}
📚 Daha fazla kod örneği göster

Views engines

📖 Settings 📖 Engines 📖 Render

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ı

📖 HTTP Methodlari

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

📖 Websocket

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!

💬 Medya

👍 Destek

Eğer teşekkür etmek ve/veya Fiber'in aktif geliştirilmesini desteklemek istiyorsanız:

  1. Projeye GitHub Yıldızı verin.
  2. Twitter hesabınızdan proje hakkında tweet atın.
  3. Medium, Dev.to veya kişisel blog üzerinden bir inceleme veya eğitici yazı yazın.
  4. API dökümantasyonunu çevirerek destek olabilirsiniz Crowdin Crowdin
  5. 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

Code Contributors

Stargazers

Stargazers over time

⚠️ 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ı