1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-23 02:24:27 +00:00
fiber/.github/README_zh-TW.md
2020-09-14 18:07:03 +01:00

32 KiB
Raw Blame History

Fiber

Fiber是移植NodeJS的Express框架改以Go語言編寫。本套件基於FasthttpFasthttp有不分配記憶體空間Request Pool的特性,在網路效能方面有著顯著的效能。

快速入門

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 👋!")
	})

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

🤖 效能

本測試使用TechEmpowerGo Web框架效能測試。如果要看全部的執行結果,請到Wiki

⚙️ 安裝

第一步, 下載並安裝Go。 請使用1.14以上版本。

下指令go get下載套件:

go get github.com/gofiber/fiber/v2

🎯 功能

💡 理念

不少Node.js的工程師跳到Go必須學習一些知識因此做了一個跟Express一樣的Fiber省這些麻煩。設計還是照原本的極簡主義還有遵循UNIX慣例,因此新手們可以無痛迅速進入Go的世界。

Fiber 受到 網路上最流行的Web框架ExpressJS啟發結合Express的易用性和Go的高效能。若你之前用過Node.js寫Web應用(使用ExpressJS/Koa或類似工具),那你已經上手了。

有什麼問題請發issues或加入Discord channel討論,我們想要創造快速彈性友善的社群給任何人使用就像Express那樣。

👀 範例

以下是一些常見範例。

更多程式碼在範例專案中或直接看API文件

📖 Basic Routing

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

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

	// 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 /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 /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 /api/register
	app.Get("/api/*", func(c *fiber.Ctx) error {
		msg := fmt.Sprintf("✋ %s", c.Params("*"))
		return c.SendString(msg) // => ✋ /api/register
	})

	log.Fatal(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

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

📖 Middleware & Next

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"))
}

📚 顯示更多範例

界面引擎

📖 設定 📖 引擎 📖 渲染

當不指定樣板引擎時Fiber預設用html/template

如果你想要執行部份或用別的樣板引擎amberhandlebarsmustachepug之類…請參考符合多樣板引擎的樣板套件。

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"))
}

Grouping routes into chains

📖 Group

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

	// ...
}

中介器logger

📖 Logger

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"))
}

跨網域資源共享 (CORS)

📖 CORS

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"))
}

Origin header中放網域來檢查CORS:

curl -H "Origin: http://example.com" --verbose http://localhost:3000

客制404回應

📖 HTTP Methods

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"))
}

JSON 回應

📖 JSON

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

import (
    "github.com/gofiber/fiber/v2"
    "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
      }
    }
  }))

  log.Fatal(app.Listen(":3000"))
  // ws://localhost:3000/ws
}

Recover 中介器

📖 Recover

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/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"))
}

🧬 Internal Middleware

Here is a list of middleware that are included within the Fiber framework.

| Middleware | Description | | 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. | | cors | Enable cross-origin resource sharing CORS with various options. | | csrf | Protect from CSRF exploits. | | filesystem | FileSystem 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. | | 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. | | 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. |

🧬 External Middleware

List of externally hosted middleware modules and maintained by the Fiber team.

Middleware Description
adaptor Converter for net/http handlers to/from Fiber request handlers, special thanks to @arsmn!
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.
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.
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!

🌱 第三方中介器

由社群建立的中介器列表要新增請發PR!

👍 貢獻

如果您要說聲謝謝或支援Fiber的積極發展:

  1. 點擊GitHub Star關注本專案。
  2. Twitter
  3. MediumDev.to、部落格上發表意見或教學。
  4. 贊助我們一杯咖啡

支持者

Fiber是一個以贊助維生的開源專案像是: 網域、gitbook、netlify、serverless伺服器。如果你想贊助也可以 買杯咖啡

User Donation
@destari x 10
@dembygenesis x 5
@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

💻 貢獻者

Code Contributors

Stargazers

Stargazers over time

⚠️ 授權

Copyright (c) 2019-present Fenny and Contributors. Fiber is free and open-source software licensed under the MIT License. Official logo was created by Vic Shóstak and distributed under Creative Commons license (CC BY-SA 4.0 International).

Third-party library licenses