mirror of https://github.com/gofiber/fiber.git
Rename structs
parent
67b16cfd65
commit
0ed4b20cfa
|
@ -1,153 +0,0 @@
|
|||
# 🚀 Fiber <a href="https://github.com/gofiber/fiber/blob/master/README.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/en.svg" alt="en"/></a> <a href="https://github.com/gofiber/fiber/blob/master/.github/README_RU.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/ru.svg" alt="ru"/></a>
|
||||
|
||||
[](https://github.com/gofiber/fiber/releases)  [](https://godoc.org/github.com/gofiber/fiber)  [](https://github.com/gofiber/fiber/blob/master/LICENSE) [](https://gitter.im/gofiber/community)
|
||||
|
||||
<img align="right" height="180px" src="https://github.com/gofiber/docs/blob/master/static/logo_320px_trans.png" alt="Fiber logo" />
|
||||
|
||||
**[Fiber](https://github.com/gofiber/fiber)** 是一个 [Express.js](https://expressjs.com/en/4x/api.html) 运行的样式化HTTP Web框架实现 [Fasthttp](https://github.com/valyala/fasthttp), **最快的** HTTP引擎 Go (Golang). 该软件包使用了**相似的框架约定** Express.
|
||||
|
||||
人们从 [Node.js](https://nodejs.org/en/about/) 至 [Go](https://golang.org/doc/) 通常会遇到学习曲线不好的问题,从而开始构建他们的Web应用程序, 这个项目是为了 **缓解** 事情准备 **快速** 发展,但与 **零内存分配** 和 **性能** 心里.
|
||||
|
||||
## API Documentation
|
||||
|
||||
📚 我们创建了一个扩展我们创建了一个扩展 **API documentation** (_包括例子_), **[点击这里](https://fiber.wiki/)**.
|
||||
|
||||
## Benchmark
|
||||
|
||||
[](https://fiber.wiki/benchmarks)
|
||||
|
||||
👉 **[点击这里](https://fiber.wiki/#/benchmarks)** 查看所有基准测试结果.
|
||||
|
||||
## Features
|
||||
|
||||
- 针对速度和低内存使用进行了优化
|
||||
- 快速的服务器端编程
|
||||
- 通过参数轻松路由
|
||||
- 具有自定义前缀的静态文件
|
||||
- 具有Next支持的中间件
|
||||
- Express API端点
|
||||
- [Extended documentation](https://fiber.wiki/)
|
||||
|
||||
## Installing
|
||||
|
||||
假设您已经安装 Go `1.11+` 😉
|
||||
|
||||
安装 [Fiber](https://github.com/gofiber/fiber) 通过调用以下命令来打包:
|
||||
|
||||
```bash
|
||||
go get -u github.com/gofiber/fiber
|
||||
```
|
||||
|
||||
## Hello, world!
|
||||
|
||||
以下代码段是您可以创建的最简单的Fiber应用程序:
|
||||
|
||||
```go
|
||||
// server.go
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/gofiber/fiber"
|
||||
|
||||
func main() {
|
||||
// Create new Fiber instance
|
||||
app := fiber.New()
|
||||
|
||||
// Create new route with GET method
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send("Hello, World!")
|
||||
})
|
||||
|
||||
// Start server on http://localhost:8080
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
||||
转到控制台并运行:
|
||||
|
||||
```bash
|
||||
go run server.go
|
||||
```
|
||||
|
||||
现在,请用浏览器打开此链接 `http://localhost:8080` 你应该看到 `Hello, World!` 在页面上! 🎉
|
||||
|
||||
## Static files
|
||||
|
||||
要提供静态文件支持,请使用 [Static](https://fiber.wiki/application#static) 方法:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/gofiber/fiber"
|
||||
|
||||
func main() {
|
||||
// Create new Fiber instance
|
||||
app := fiber.New()
|
||||
|
||||
// Serve all static files on ./public folder
|
||||
app.Static("./public")
|
||||
|
||||
// Start server on http://localhost:8080
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
||||
现在,您可以加载公共目录中的文件:
|
||||
|
||||
```bash
|
||||
http://localhost:8080/hello.html
|
||||
http://localhost:8080/js/script.js
|
||||
http://localhost:8080/css/style.css
|
||||
```
|
||||
|
||||
## Middleware
|
||||
|
||||
中间件从未如此简单!就像Express,向Express `Next()`致敬:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/gofiber/fiber"
|
||||
|
||||
func main() {
|
||||
// Create new Fiber instance
|
||||
app := fiber.New()
|
||||
|
||||
// Define all used middlewares in Use()
|
||||
|
||||
app.Use(func(c *fiber.Ctx) {
|
||||
c.Write("Match anything!\n")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
app.Use("/api", func(c *fiber.Ctx) {
|
||||
c.Write("Match starting with /api\n")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
app.Get("/api/user", func(c *fiber.Ctx) {
|
||||
c.Write("Match exact path /api/user\n")
|
||||
})
|
||||
|
||||
// Start server on http://localhost:8080
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
||||
## Project assistance
|
||||
|
||||
如果您要说声谢谢或者积极支持fiber的发展 `gofiber/fiber`:
|
||||
|
||||
1. 将GitHub Star添加到项目中。
|
||||
2. 关于项目的推文 [on your Twitter](https://twitter.com/intent/tweet?text=%F0%9F%94%8C%20Fiber%20is%20an%20Express.js%20inspired%20Go%20web%20framework%20build%20on%20%F0%9F%9A%80%20Fasthttp%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
|
||||
3. 帮助我们翻译 `README` 和 [API Docs](https://fiber.wiki/) 换一种语言.
|
||||
|
||||
谢谢你的支持! 😘 我们在一起 `Fiber Web Framework` 每天都好.
|
||||
|
||||
## Stargazers over time
|
||||
|
||||
[](https://starchart.cc/gofiber/fiber)
|
||||
|
||||
## License
|
||||
|
||||
⚠️ _请注意:_ `gofiber/fiber` 是根据以下条款获得许可的免费开源软件 [MIT License](https://github.com/gofiber/fiber/master/LICENSE).
|
|
@ -1,154 +0,0 @@
|
|||
# 🚀 Fiber <a href="https://github.com/gofiber/fiber/blob/master/README.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/en.svg" alt="en"/></a> <a href="https://github.com/gofiber/fiber/blob/master/.github/README_CH.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/ch.svg" alt="ch"/></a>
|
||||
|
||||
[](https://github.com/gofiber/fiber/releases)  [](https://godoc.org/github.com/gofiber/fiber)  [](https://github.com/gofiber/fiber/blob/master/LICENSE) [](https://gitter.im/gofiber/community)
|
||||
|
||||
<img align="right" height="180px" src="https://github.com/gofiber/docs/blob/master/static/logo_320px_trans.png" alt="Fiber logo" />
|
||||
|
||||
**[Fiber](https://github.com/gofiber/fiber)** — это [Express.js](https://expressjs.com/en/4x/api.html) подобный HTTP веб фреймворк, использующий всю мощь [Fasthttp](https://github.com/valyala/fasthttp), самого **быстрого** HTTP движка для Go (Golang). Мы используем **аналогичную** схему именования методов, как и у Express.
|
||||
|
||||
Разработчики, пришедшие из [Node.js](https://nodejs.org/en/about/) в [Go](https://golang.org/doc/) очень часто испытывают трудности при создании своих первых веб-приложений. Данный проект призван, в том числе, **облегчить** процесс перехода для таких разработчиков.
|
||||
|
||||
## Документация по API
|
||||
|
||||
📚 Мы создали расширенную **документацию по API** (_включая примеры_), **[посмотреть](https://fiber.wiki/)**.
|
||||
|
||||
## Бенчмарк
|
||||
|
||||
[](https://fiber.wiki/benchmarks)
|
||||
|
||||
👉 **[Click here](https://fiber.wiki/benchmarks)** to see all benchmark results.
|
||||
|
||||
## Особенности
|
||||
|
||||
- Оптимизирован для скорости и низкого использования памяти
|
||||
- Быстрое Server-Side программирование
|
||||
- Простая маршрутизация с параметрами
|
||||
- Статические файлы с пользовательским префиксом
|
||||
- Middleware с поддержкой `Next()`
|
||||
- Endpoints, как у API Express
|
||||
- [Расширенная документация](https://fiber.wiki/)
|
||||
|
||||
## Установка
|
||||
|
||||
Предположим, вы уже установили Go `1.11+` 😉
|
||||
|
||||
Установит пакет [Fiber](https://github.com/gofiber/fiber) с помощью следующей команды в консоле:
|
||||
|
||||
```bash
|
||||
go get -u github.com/gofiber/fiber
|
||||
```
|
||||
|
||||
## Hello, world!
|
||||
|
||||
Веб-приложение ниже, по сути, является самым простым приложением, которое вы можете создать:
|
||||
|
||||
```go
|
||||
// server.go
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/gofiber/fiber"
|
||||
|
||||
func main() {
|
||||
// Создание нового инстанса Fiber
|
||||
app := fiber.New()
|
||||
|
||||
// Создание маршрута с GET
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send("Hello, World!")
|
||||
})
|
||||
|
||||
// Старт сервера на http://localhost:8080
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
||||
Перейдите в консоль и запустите:
|
||||
|
||||
```bash
|
||||
go run server.go
|
||||
```
|
||||
|
||||
А теперь, откройте в браузере адрес `http://localhost:8080`. Вы должы увидеть надпись `Hello, World!`! 🎉
|
||||
|
||||
## Статичные файлы
|
||||
|
||||
Для получения доступа к статичным файлам, используйте метод [Static](https://fiber.wiki/application#static):
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/gofiber/fiber"
|
||||
|
||||
func main() {
|
||||
// Создание нового инстанса Fiber
|
||||
app := fiber.New()
|
||||
|
||||
// Включение всех файлов в папке ./public для работы
|
||||
app.Static("./public")
|
||||
|
||||
// Старт сервера на http://localhost:8080
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
||||
Теперь вы можете получить доступ ко всем файлам, которые находятся в папке `./public`:
|
||||
|
||||
```bash
|
||||
http://localhost:8080/hello.html
|
||||
http://localhost:8080/js/script.js
|
||||
http://localhost:8080/css/style.css
|
||||
```
|
||||
|
||||
## Middleware
|
||||
|
||||
Еще никогда работа с middleware не была настолько простой! Так же, как и в Express, вы должны вызывать метод `Next()` для дальнейшего следования по маршрутам роутера:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/gofiber/fiber"
|
||||
|
||||
func main() {
|
||||
// Создание нового инстанса Fiber
|
||||
app := fiber.New()
|
||||
|
||||
// Определяем все необходимые middlewares
|
||||
// с помощью метода Use()
|
||||
|
||||
app.Use(func(c *fiber.Ctx) {
|
||||
c.Write("Match anything!\n")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
app.Use("/api", func(c *fiber.Ctx) {
|
||||
c.Write("Match starting with /api\n")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
app.Get("/api/user", func(c *fiber.Ctx) {
|
||||
c.Write("Match exact path /api/user\n")
|
||||
})
|
||||
|
||||
// Старт сервера на http://localhost:8080
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
||||
## Помощь проекту
|
||||
|
||||
Если вы хотите сказать «спасибо» и/или помочь активной разработке `gofiber/fiber`:
|
||||
|
||||
1. Добавьте звёздочку GitHub этому репозиторию.
|
||||
2. Отправьте твит об этом проекте [в свой Twitter](https://twitter.com/intent/tweet?text=%F0%9F%94%8C%20Fiber%20is%20an%20Express.js%20inspired%20Go%20web%20framework%20build%20on%20%F0%9F%9A%80%20Fasthttp%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
|
||||
3. Помогите нам перевести `README` и [Документацию по API](https://fiber.wiki/) на другой язык.
|
||||
|
||||
Спасибо за поддержку! 😘 Вместе мы делаем `Fiber Web Framework` лучше каждый день.
|
||||
|
||||
## Звёздочки с течением времени
|
||||
|
||||
[](https://starchart.cc/gofiber/fiber)
|
||||
|
||||
## Лицензия
|
||||
|
||||
⚠️ _Обратите внимание:_ `gofiber/fiber` является свободным программным обеспечением с открытым исходным кодом, лицензируемым в соответствии с [MIT License](LICENSE).
|
|
@ -0,0 +1,408 @@
|
|||
<img alt="Fiber" src="https://i.imgur.com/Nwvx4cu.png" width="250"/><a href="https://github.com/gofiber/fiber/blob/master/README.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/en.svg" alt="en"/></a> <a href="https://github.com/gofiber/fiber/blob/master/.github/README_CH.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/ch.svg" alt="ch"/></a>
|
||||
|
||||
[](https://github.com/gofiber/fiber/releases) [](https://fiber.wiki)  [](https://gocover.io/github.com/gofiber/fiber) [](https://travis-ci.org/gofiber/fiber) [](https://travis-ci.org/gofiber/fiber)
|
||||
|
||||
**Fiber** is an [Expressjs](https://github.com/expressjs/express) inspired **web framework** build on top of [Fasthttp](https://github.com/valyala/fasthttp), the **fastest** HTTP engine for [Go](https://golang.org/doc/). Designed to **ease** things up for **fast** development with **zero memory allocation** and **performance** in mind.
|
||||
|
||||
## ⚡️ Quick start
|
||||
|
||||
```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)
|
||||
}
|
||||
```
|
||||
|
||||
## ⚙️ Installation
|
||||
|
||||
First of all, [download](https://golang.org/dl/) and install Go. `1.11` or higher is required.
|
||||
|
||||
Installation is done using the [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) command:
|
||||
|
||||
```bash
|
||||
go get github.com/gofiber/fiber
|
||||
```
|
||||
|
||||
## 🤖 Benchmarks
|
||||
|
||||
These tests are performed by [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) and [Go Web](https://github.com/smallnest/go-web-framework-benchmark). If you want to see all results, please visit our [Wiki](https://fiber.wiki/benchmarks).
|
||||
|
||||
<p float="left" align="middle">
|
||||
<img src="https://github.com/gofiber/docs/blob/master/static/benchmarks/benchmark-pipeline.png" width="49%" />
|
||||
<img src="https://github.com/gofiber/docs/blob/master/static/benchmarks/benchmark_alloc.png" width="49%" />
|
||||
</p>
|
||||
|
||||
## 🎯 Features
|
||||
|
||||
- Robust [routing](https://fiber.wiki/routing)
|
||||
- Serve [static files](https://fiber.wiki/application#static)
|
||||
- Extreme [performance](https://fiber.wiki/benchmarks)
|
||||
- [Low memory](https://fiber.wiki/benchmarks) footprint
|
||||
- Express [API endpoints](https://fiber.wiki/context)
|
||||
- Middleware & [Next](https://fiber.wiki/context#next) support
|
||||
- [Rapid](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) server-side programming
|
||||
- And much more, [explore Fiber](https://fiber.wiki/)
|
||||
|
||||
## 💡 Philosophy
|
||||
|
||||
New gophers that make the switch from [Node.js](https://nodejs.org/en/about/) to [Go](https://golang.org/doc/) are dealing with a learning curve before they can start building their web applications or microservices. Fiber, as a **web framework**, was created with the idea of **minimalism** and follow **UNIX way**, so that new gophers can quickly enter the world of Go with a warm and trusted welcome.
|
||||
|
||||
Fiber is **inspired** by the Expressjs, the most popular web framework on Internet. We combined the **ease** of Express and **raw performance** of Go. If you have ever implemented a web application on Node.js (_using Express.js or similar_), then many methods and principles will seem **very common** to you.
|
||||
|
||||
## 👀 Examples
|
||||
|
||||
Listed below are some of the common examples. If you want to see more code examples, please visit our [Recipes repository](https://github.com/gofiber/recipes) or visit our [API documentation](https://fiber.wiki).
|
||||
|
||||
### Static files
|
||||
|
||||
```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.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### 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)
|
||||
}
|
||||
```
|
||||
|
||||
### Middleware
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Match any post route
|
||||
app.Post(func(c *fiber.Ctx) {
|
||||
user, pass, ok := c.BasicAuth()
|
||||
if !ok || user != "john" || pass != "doe" {
|
||||
c.Status(403).Send("Sorry John")
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) {
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Headers", "X-Requested-With")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Optional param
|
||||
app.Post("/api/register", func(c *fiber.Ctx) {
|
||||
username := c.Body("username")
|
||||
password := c.Body("password")
|
||||
// ..
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### 404 Handling
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Serve static files from "public" directory
|
||||
app.Static("./public")
|
||||
|
||||
// Last middleware
|
||||
app.Use(func (c *fiber.Ctx) {
|
||||
c.SendStatus(404) // => 404 "Not Found"
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### JSON Response
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
// Serialize JSON
|
||||
app.Get("/json", func (c *fiber.Ctx) {
|
||||
c.JSON(&User{"John", 20})
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
## 💬 Media
|
||||
|
||||
- [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_
|
||||
|
||||
## 👍 Contribute
|
||||
|
||||
If you want to say **thank you** and/or support the active development of `fiber`:
|
||||
|
||||
1. Add a [GitHub Star](https://github.com/gofiber/fiber/stargazers) to project.
|
||||
2. Tweet about project [on your 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. Write a review or tutorial on [Medium](https://medium.com/), [Dev.to](https://dev.to/) or personal blog.
|
||||
4. Help us to translate this `README` and [API Docs](https://fiber.wiki/) to another language.
|
||||
|
||||
<a href="https://www.buymeacoffee.com/fenny" target="_blank"><img src="https://github.com/gofiber/docs/blob/master/static/buy-morning-coffee-3x.gif" alt="Buy Me A Coffee" style="height: 35px !important;" ></a>
|
||||
|
||||
### ⭐️ Stars
|
||||
|
||||
<a href="https://starchart.cc/gofiber/fiber" rel="nofollow"><img src="https://starchart.cc/gofiber/fiber.svg" alt="Stars over time" style="max-width:100%;"></a>
|
||||
|
||||
## ⚠️ License
|
||||
|
||||
`Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/master/LICENSE).
|
||||
<img alt="Fiber" src="https://i.imgur.com/Nwvx4cu.png" width="250"/><a href="https://github.com/gofiber/fiber/blob/master/.github/README_RU.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/ru.svg" alt="ru"/></a> <a href="https://github.com/gofiber/fiber/blob/master/.github/README_CH.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/ch.svg" alt="ch"/></a>
|
||||
|
||||
[](https://github.com/gofiber/fiber/releases) [](https://fiber.wiki)  [](https://gocover.io/github.com/gofiber/fiber) [](https://travis-ci.org/gofiber/fiber) [](https://travis-ci.org/gofiber/fiber)
|
||||
|
||||
**Fiber** is an [Expressjs](https://github.com/expressjs/express) inspired **web framework** build on top of [Fasthttp](https://github.com/valyala/fasthttp), the **fastest** HTTP engine for [Go](https://golang.org/doc/). Designed to **ease** things up for **fast** development with **zero memory allocation** and **performance** in mind.
|
||||
|
||||
## ⚡️ Quick start
|
||||
|
||||
```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)
|
||||
}
|
||||
```
|
||||
|
||||
## ⚙️ Installation
|
||||
|
||||
First of all, [download](https://golang.org/dl/) and install Go. `1.11` or higher is required.
|
||||
|
||||
Installation is done using the [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) command:
|
||||
|
||||
```bash
|
||||
go get github.com/gofiber/fiber
|
||||
```
|
||||
|
||||
## 🤖 Benchmarks
|
||||
|
||||
These tests are performed by [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) and [Go Web](https://github.com/smallnest/go-web-framework-benchmark). If you want to see all results, please visit our [Wiki](https://fiber.wiki/benchmarks).
|
||||
|
||||
<p float="left" align="middle">
|
||||
<img src="https://github.com/gofiber/docs/blob/master/static/benchmarks/benchmark-pipeline.png" width="49%" />
|
||||
<img src="https://github.com/gofiber/docs/blob/master/static/benchmarks/benchmark_alloc.png" width="49%" />
|
||||
</p>
|
||||
|
||||
## 🎯 Features
|
||||
|
||||
- Robust [routing](https://fiber.wiki/routing)
|
||||
- Serve [static files](https://fiber.wiki/application#static)
|
||||
- Extreme [performance](https://fiber.wiki/benchmarks)
|
||||
- [Low memory](https://fiber.wiki/benchmarks) footprint
|
||||
- Express [API endpoints](https://fiber.wiki/context)
|
||||
- Middleware & [Next](https://fiber.wiki/context#next) support
|
||||
- [Rapid](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) server-side programming
|
||||
- And much more, [explore Fiber](https://fiber.wiki/)
|
||||
|
||||
## 💡 Philosophy
|
||||
|
||||
New gophers that make the switch from [Node.js](https://nodejs.org/en/about/) to [Go](https://golang.org/doc/) are dealing with a learning curve before they can start building their web applications or microservices. Fiber, as a **web framework**, was created with the idea of **minimalism** and follow **UNIX way**, so that new gophers can quickly enter the world of Go with a warm and trusted welcome.
|
||||
|
||||
Fiber is **inspired** by the Expressjs, the most popular web framework on Internet. We combined the **ease** of Express and **raw performance** of Go. If you have ever implemented a web application on Node.js (_using Express.js or similar_), then many methods and principles will seem **very common** to you.
|
||||
|
||||
## 👀 Examples
|
||||
|
||||
Listed below are some of the common examples. If you want to see more code examples, please visit our [Recipes repository](https://github.com/gofiber/recipes) or visit our [API documentation](https://fiber.wiki).
|
||||
|
||||
### Static files
|
||||
|
||||
```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.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### 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)
|
||||
}
|
||||
```
|
||||
|
||||
### Middleware
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Match any post route
|
||||
app.Post(func(c *fiber.Ctx) {
|
||||
user, pass, ok := c.BasicAuth()
|
||||
if !ok || user != "john" || pass != "doe" {
|
||||
c.Status(403).Send("Sorry John")
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) {
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Headers", "X-Requested-With")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Optional param
|
||||
app.Post("/api/register", func(c *fiber.Ctx) {
|
||||
username := c.Body("username")
|
||||
password := c.Body("password")
|
||||
// ..
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### 404 Handling
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Serve static files from "public" directory
|
||||
app.Static("./public")
|
||||
|
||||
// Last middleware
|
||||
app.Use(func (c *fiber.Ctx) {
|
||||
c.SendStatus(404) // => 404 "Not Found"
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### JSON Response
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
// Serialize JSON
|
||||
app.Get("/json", func (c *fiber.Ctx) {
|
||||
c.JSON(&User{"John", 20})
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
## 💬 Media
|
||||
|
||||
- [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_
|
||||
|
||||
## 👍 Contribute
|
||||
|
||||
If you want to say **thank you** and/or support the active development of `fiber`:
|
||||
|
||||
1. Add a [GitHub Star](https://github.com/gofiber/fiber/stargazers) to project.
|
||||
2. Tweet about project [on your 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. Write a review or tutorial on [Medium](https://medium.com/), [Dev.to](https://dev.to/) or personal blog.
|
||||
4. Help us to translate this `README` and [API Docs](https://fiber.wiki/) to another language.
|
||||
|
||||
<a href="https://www.buymeacoffee.com/fenny" target="_blank"><img src="https://github.com/gofiber/docs/blob/master/static/buy-morning-coffee-3x.gif" alt="Buy Me A Coffee" style="height: 35px !important;" ></a>
|
||||
|
||||
### ⭐️ Stars
|
||||
|
||||
<a href="https://starchart.cc/gofiber/fiber" rel="nofollow"><img src="https://starchart.cc/gofiber/fiber.svg" alt="Stars over time" style="max-width:100%;"></a>
|
||||
|
||||
## ⚠️ License
|
||||
|
||||
`Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/master/LICENSE).
|
|
@ -0,0 +1,204 @@
|
|||
<img alt="Fiber" src="https://i.imgur.com/Nwvx4cu.png" width="250"/><a href="https://github.com/gofiber/fiber/blob/master/README.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/en.svg" alt="en"/></a> <a href="https://github.com/gofiber/fiber/blob/master/.github/README_RU.md"><img width="20px" src="https://github.com/gofiber/docs/blob/master/static/flags/ru.svg" alt="ru"/></a>
|
||||
|
||||
[](https://github.com/gofiber/fiber/releases) [](https://fiber.wiki)  [](https://gocover.io/github.com/gofiber/fiber) [](https://travis-ci.org/gofiber/fiber) [](https://travis-ci.org/gofiber/fiber)
|
||||
|
||||
**Fiber** is an [Expressjs](https://github.com/expressjs/express) inspired **web framework** build on top of [Fasthttp](https://github.com/valyala/fasthttp), the **fastest** HTTP engine for [Go](https://golang.org/doc/). Designed to **ease** things up for **fast** development with **zero memory allocation** and **performance** in mind.
|
||||
|
||||
## ⚡️ Quick start
|
||||
|
||||
```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)
|
||||
}
|
||||
```
|
||||
|
||||
## ⚙️ Installation
|
||||
|
||||
First of all, [download](https://golang.org/dl/) and install Go. `1.11` or higher is required.
|
||||
|
||||
Installation is done using the [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) command:
|
||||
|
||||
```bash
|
||||
go get github.com/gofiber/fiber
|
||||
```
|
||||
|
||||
## 🤖 Benchmarks
|
||||
|
||||
These tests are performed by [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) and [Go Web](https://github.com/smallnest/go-web-framework-benchmark). If you want to see all results, please visit our [Wiki](https://fiber.wiki/benchmarks).
|
||||
|
||||
<p float="left" align="middle">
|
||||
<img src="https://github.com/gofiber/docs/blob/master/static/benchmarks/benchmark-pipeline.png" width="49%" />
|
||||
<img src="https://github.com/gofiber/docs/blob/master/static/benchmarks/benchmark_alloc.png" width="49%" />
|
||||
</p>
|
||||
|
||||
## 🎯 Features
|
||||
|
||||
- Robust [routing](https://fiber.wiki/routing)
|
||||
- Serve [static files](https://fiber.wiki/application#static)
|
||||
- Extreme [performance](https://fiber.wiki/benchmarks)
|
||||
- [Low memory](https://fiber.wiki/benchmarks) footprint
|
||||
- Express [API endpoints](https://fiber.wiki/context)
|
||||
- Middleware & [Next](https://fiber.wiki/context#next) support
|
||||
- [Rapid](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) server-side programming
|
||||
- And much more, [explore Fiber](https://fiber.wiki/)
|
||||
|
||||
## 💡 Philosophy
|
||||
|
||||
New gophers that make the switch from [Node.js](https://nodejs.org/en/about/) to [Go](https://golang.org/doc/) are dealing with a learning curve before they can start building their web applications or microservices. Fiber, as a **web framework**, was created with the idea of **minimalism** and follow **UNIX way**, so that new gophers can quickly enter the world of Go with a warm and trusted welcome.
|
||||
|
||||
Fiber is **inspired** by the Expressjs, the most popular web framework on Internet. We combined the **ease** of Express and **raw performance** of Go. If you have ever implemented a web application on Node.js (_using Express.js or similar_), then many methods and principles will seem **very common** to you.
|
||||
|
||||
## 👀 Examples
|
||||
|
||||
Listed below are some of the common examples. If you want to see more code examples, please visit our [Recipes repository](https://github.com/gofiber/recipes) or visit our [API documentation](https://fiber.wiki).
|
||||
|
||||
### Static files
|
||||
|
||||
```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.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### 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)
|
||||
}
|
||||
```
|
||||
|
||||
### Middleware
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Match any post route
|
||||
app.Post(func(c *fiber.Ctx) {
|
||||
user, pass, ok := c.BasicAuth()
|
||||
if !ok || user != "john" || pass != "doe" {
|
||||
c.Status(403).Send("Sorry John")
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) {
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Headers", "X-Requested-With")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Optional param
|
||||
app.Post("/api/register", func(c *fiber.Ctx) {
|
||||
username := c.Body("username")
|
||||
password := c.Body("password")
|
||||
// ..
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### 404 Handling
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Serve static files from "public" directory
|
||||
app.Static("./public")
|
||||
|
||||
// Last middleware
|
||||
app.Use(func (c *fiber.Ctx) {
|
||||
c.SendStatus(404) // => 404 "Not Found"
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
### JSON Response
|
||||
|
||||
```go
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
// Serialize JSON
|
||||
app.Get("/json", func (c *fiber.Ctx) {
|
||||
c.JSON(&User{"John", 20})
|
||||
})
|
||||
|
||||
app.Listen(3000)
|
||||
}
|
||||
```
|
||||
|
||||
## 💬 Media
|
||||
|
||||
- [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_
|
||||
|
||||
## 👍 Contribute
|
||||
|
||||
If you want to say **thank you** and/or support the active development of `fiber`:
|
||||
|
||||
1. Add a [GitHub Star](https://github.com/gofiber/fiber/stargazers) to project.
|
||||
2. Tweet about project [on your 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. Write a review or tutorial on [Medium](https://medium.com/), [Dev.to](https://dev.to/) or personal blog.
|
||||
4. Help us to translate this `README` and [API Docs](https://fiber.wiki/) to another language.
|
||||
|
||||
<a href="https://www.buymeacoffee.com/fenny" target="_blank"><img src="https://github.com/gofiber/docs/blob/master/static/buy-morning-coffee-3x.gif" alt="Buy Me A Coffee" style="height: 35px !important;" ></a>
|
||||
|
||||
### ⭐️ Stars
|
||||
|
||||
<a href="https://starchart.cc/gofiber/fiber" rel="nofollow"><img src="https://starchart.cc/gofiber/fiber.svg" alt="Stars over time" style="max-width:100%;"></a>
|
||||
|
||||
## ⚠️ License
|
||||
|
||||
`Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/master/LICENSE).
|
299
application.go
299
application.go
|
@ -8,10 +8,14 @@
|
|||
package fiber
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
@ -20,23 +24,20 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/valyala/fasthttp"
|
||||
"github.com/valyala/fasthttp/reuseport"
|
||||
)
|
||||
|
||||
const (
|
||||
// Version : Fiber version
|
||||
Version = "1.4.2"
|
||||
website = "https://fiber.wiki"
|
||||
banner = ` ______ __ ______ ______ ______
|
||||
Version = "1.4.3"
|
||||
banner = "\x1b[1;32m" + ` ______ __ ______ ______ ______
|
||||
/\ ___\ /\ \ /\ == \ /\ ___\ /\ == \
|
||||
\ \ __\ \ \ \ \ \ __< \ \ __\ \ \ __<
|
||||
\ \_\ \ \_\ \ \_____\ \ \_____\ \ \_\ \_\
|
||||
\/_/ \/_/ \/_____/ \/_____/ \/_/ /_/
|
||||
|
||||
%sFiber %s listening on %s, visit %s
|
||||
`
|
||||
` + "\x1b[1;30mFiber \x1b[1;32mv%s\x1b[1;30m %s on \x1b[1;32m%s\x1b[1;30m, visit \x1b[1;32m%s\x1b[0m\n\n"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -44,8 +45,8 @@ var (
|
|||
child = flag.Bool("child", false, "is child process")
|
||||
)
|
||||
|
||||
// Fiber structure
|
||||
type Fiber struct {
|
||||
// Application structure
|
||||
type Application struct {
|
||||
// Server name header
|
||||
Server string
|
||||
httpServer *fasthttp.Server
|
||||
|
@ -84,9 +85,9 @@ type engine struct {
|
|||
}
|
||||
|
||||
// New https://fiber.wiki/application#new
|
||||
func New() *Fiber {
|
||||
func New() *Application {
|
||||
flag.Parse()
|
||||
return &Fiber{
|
||||
return &Application{
|
||||
Server: "",
|
||||
httpServer: nil,
|
||||
Banner: true,
|
||||
|
@ -117,159 +118,159 @@ func New() *Fiber {
|
|||
|
||||
// Group :
|
||||
type Group struct {
|
||||
path string
|
||||
fiber *Fiber
|
||||
path string
|
||||
app *Application
|
||||
}
|
||||
|
||||
// Group :
|
||||
func (f *Fiber) Group(path string) *Group {
|
||||
func (app *Application) Group(path string) *Group {
|
||||
return &Group{
|
||||
path: path,
|
||||
fiber: f,
|
||||
path: path,
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
// Connect establishes a tunnel to the server
|
||||
// identified by the target resource.
|
||||
func (f *Fiber) Connect(args ...interface{}) *Fiber {
|
||||
f.register("CONNECT", args...)
|
||||
return f
|
||||
func (app *Application) Connect(args ...interface{}) *Application {
|
||||
app.register("CONNECT", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Connect for group
|
||||
func (g *Group) Connect(args ...interface{}) *Group {
|
||||
g.register("CONNECT", args...)
|
||||
return g
|
||||
func (grp *Group) Connect(args ...interface{}) *Group {
|
||||
grp.register("CONNECT", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Put replaces all current representations
|
||||
// of the target resource with the request payload.
|
||||
func (f *Fiber) Put(args ...interface{}) *Fiber {
|
||||
f.register("PUT", args...)
|
||||
return f
|
||||
func (app *Application) Put(args ...interface{}) *Application {
|
||||
app.register("PUT", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Put for group
|
||||
func (g *Group) Put(args ...interface{}) *Group {
|
||||
g.register("PUT", args...)
|
||||
return g
|
||||
func (grp *Group) Put(args ...interface{}) *Group {
|
||||
grp.register("PUT", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Post is used to submit an entity to the specified resource,
|
||||
// often causing a change in state or side effects on the server.
|
||||
func (f *Fiber) Post(args ...interface{}) *Fiber {
|
||||
f.register("POST", args...)
|
||||
return f
|
||||
func (app *Application) Post(args ...interface{}) *Application {
|
||||
app.register("POST", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Post for group
|
||||
func (g *Group) Post(args ...interface{}) *Group {
|
||||
g.register("POST", args...)
|
||||
return g
|
||||
func (grp *Group) Post(args ...interface{}) *Group {
|
||||
grp.register("POST", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Delete deletes the specified resource.
|
||||
func (f *Fiber) Delete(args ...interface{}) *Fiber {
|
||||
f.register("DELETE", args...)
|
||||
return f
|
||||
func (app *Application) Delete(args ...interface{}) *Application {
|
||||
app.register("DELETE", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Delete for group
|
||||
func (g *Group) Delete(args ...interface{}) *Group {
|
||||
g.register("DELETE", args...)
|
||||
return g
|
||||
func (grp *Group) Delete(args ...interface{}) *Group {
|
||||
grp.register("DELETE", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Head asks for a response identical to that of a GET request,
|
||||
// but without the response body.
|
||||
func (f *Fiber) Head(args ...interface{}) *Fiber {
|
||||
f.register("HEAD", args...)
|
||||
return f
|
||||
func (app *Application) Head(args ...interface{}) *Application {
|
||||
app.register("HEAD", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Head for group
|
||||
func (g *Group) Head(args ...interface{}) *Group {
|
||||
g.register("HEAD", args...)
|
||||
return g
|
||||
func (grp *Group) Head(args ...interface{}) *Group {
|
||||
grp.register("HEAD", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Patch is used to apply partial modifications to a resource.
|
||||
func (f *Fiber) Patch(args ...interface{}) *Fiber {
|
||||
f.register("PATCH", args...)
|
||||
return f
|
||||
func (app *Application) Patch(args ...interface{}) *Application {
|
||||
app.register("PATCH", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Patch for group
|
||||
func (g *Group) Patch(args ...interface{}) *Group {
|
||||
g.register("PATCH", args...)
|
||||
return g
|
||||
func (grp *Group) Patch(args ...interface{}) *Group {
|
||||
grp.register("PATCH", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Options is used to describe the communication options
|
||||
// for the target resource.
|
||||
func (f *Fiber) Options(args ...interface{}) *Fiber {
|
||||
f.register("OPTIONS", args...)
|
||||
return f
|
||||
func (app *Application) Options(args ...interface{}) *Application {
|
||||
app.register("OPTIONS", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Options for group
|
||||
func (g *Group) Options(args ...interface{}) *Group {
|
||||
g.register("OPTIONS", args...)
|
||||
return g
|
||||
func (grp *Group) Options(args ...interface{}) *Group {
|
||||
grp.register("OPTIONS", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Trace performs a message loop-back test
|
||||
// along the path to the target resource.
|
||||
func (f *Fiber) Trace(args ...interface{}) *Fiber {
|
||||
f.register("TRACE", args...)
|
||||
return f
|
||||
func (app *Application) Trace(args ...interface{}) *Application {
|
||||
app.register("TRACE", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Trace for group
|
||||
func (g *Group) Trace(args ...interface{}) *Group {
|
||||
g.register("TRACE", args...)
|
||||
return g
|
||||
func (grp *Group) Trace(args ...interface{}) *Group {
|
||||
grp.register("TRACE", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Get requests a representation of the specified resource.
|
||||
// Requests using GET should only retrieve data.
|
||||
func (f *Fiber) Get(args ...interface{}) *Fiber {
|
||||
f.register("GET", args...)
|
||||
return f
|
||||
func (app *Application) Get(args ...interface{}) *Application {
|
||||
app.register("GET", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Get for group
|
||||
func (g *Group) Get(args ...interface{}) *Group {
|
||||
g.register("GET", args...)
|
||||
return g
|
||||
func (grp *Group) Get(args ...interface{}) *Group {
|
||||
grp.register("GET", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// All matches any HTTP method
|
||||
func (f *Fiber) All(args ...interface{}) *Fiber {
|
||||
f.register("ALL", args...)
|
||||
return f
|
||||
func (app *Application) All(args ...interface{}) *Application {
|
||||
app.register("ALL", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// All for group
|
||||
func (g *Group) All(args ...interface{}) *Group {
|
||||
g.register("ALL", args...)
|
||||
return g
|
||||
func (grp *Group) All(args ...interface{}) *Group {
|
||||
grp.register("ALL", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Use only matches the starting path
|
||||
func (f *Fiber) Use(args ...interface{}) *Fiber {
|
||||
f.register("USE", args...)
|
||||
return f
|
||||
func (app *Application) Use(args ...interface{}) *Application {
|
||||
app.register("USE", args...)
|
||||
return app
|
||||
}
|
||||
|
||||
// Use for group
|
||||
func (g *Group) Use(args ...interface{}) *Group {
|
||||
g.register("USE", args...)
|
||||
return g
|
||||
func (grp *Group) Use(args ...interface{}) *Group {
|
||||
grp.register("USE", args...)
|
||||
return grp
|
||||
}
|
||||
|
||||
// Static https://fiber.wiki/application#static
|
||||
func (f *Fiber) Static(args ...string) {
|
||||
func (app *Application) Static(args ...string) {
|
||||
prefix := "/"
|
||||
root := "./"
|
||||
wildcard := false
|
||||
|
@ -324,20 +325,20 @@ func (f *Fiber) Static(args ...string) {
|
|||
|
||||
// If the file is an index.html, bind the prefix to index.html directly
|
||||
if filepath.Base(filePath) == "index.html" || filepath.Base(filePath) == "index.htm" {
|
||||
f.routes = append(f.routes, &Route{"GET", prefix, wildcard, false, nil, nil, func(c *Ctx) {
|
||||
app.routes = append(app.routes, &Route{"GET", prefix, wildcard, false, nil, nil, func(c *Ctx) {
|
||||
c.SendFile(filePath, gzip)
|
||||
}})
|
||||
}
|
||||
|
||||
// Add the route + SendFile(filepath) to routes
|
||||
f.routes = append(f.routes, &Route{"GET", path, wildcard, false, nil, nil, func(c *Ctx) {
|
||||
app.routes = append(app.routes, &Route{"GET", path, wildcard, false, nil, nil, func(c *Ctx) {
|
||||
c.SendFile(filePath, gzip)
|
||||
}})
|
||||
}
|
||||
}
|
||||
|
||||
// Listen : https://fiber.wiki/application#listen
|
||||
func (f *Fiber) Listen(address interface{}, tls ...string) {
|
||||
func (app *Application) Listen(address interface{}, tls ...string) {
|
||||
host := ""
|
||||
switch val := address.(type) {
|
||||
case int:
|
||||
|
@ -351,22 +352,19 @@ func (f *Fiber) Listen(address interface{}, tls ...string) {
|
|||
log.Fatal("Listen: Host must be an INT port or STRING address")
|
||||
}
|
||||
// Create fasthttp server
|
||||
f.httpServer = f.setupServer()
|
||||
|
||||
out := colorable.NewColorableStdout()
|
||||
app.httpServer = app.setupServer()
|
||||
|
||||
// Prefork enabled
|
||||
if f.Prefork && runtime.NumCPU() > 1 {
|
||||
if f.Banner && f.child {
|
||||
//cores := fmt.Sprintf("%s\x1b[1;30m %v cores", host, runtime.NumCPU())
|
||||
fmt.Fprintf(out, "\x1b[1;32m"+banner, "\x1b[1;30m", "\x1b[1;32mv"+Version+"\x1b[1;30m", "\x1b[1;32m"+host+"\x1b[1;30m", "\x1b[1;32mfiber.wiki")
|
||||
if app.Prefork && runtime.NumCPU() > 1 {
|
||||
if app.Banner && !app.child {
|
||||
fmt.Printf(banner, Version, "preforking", host, "fiber.wiki")
|
||||
}
|
||||
f.prefork(host, tls...)
|
||||
app.prefork(host, tls...)
|
||||
}
|
||||
|
||||
// Prefork disabled
|
||||
if f.Banner {
|
||||
fmt.Fprintf(out, "\x1b[1;32m"+banner, "\x1b[1;30m", "\x1b[1;32mv"+Version+"\x1b[1;30m", "\x1b[1;32m"+host+"\x1b[1;30m", "\x1b[1;32mfiber.wiki")
|
||||
if app.Banner {
|
||||
fmt.Printf(banner, Version, "listening", host, "fiber.wiki")
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp4", host)
|
||||
|
@ -376,28 +374,77 @@ func (f *Fiber) Listen(address interface{}, tls ...string) {
|
|||
|
||||
// enable TLS/HTTPS
|
||||
if len(tls) > 1 {
|
||||
if err := f.httpServer.ServeTLS(ln, tls[0], tls[1]); err != nil {
|
||||
if err := app.httpServer.ServeTLS(ln, tls[0], tls[1]); err != nil {
|
||||
log.Fatal("Listen: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := f.httpServer.Serve(ln); err != nil {
|
||||
if err := app.httpServer.Serve(ln); err != nil {
|
||||
log.Fatal("Listen: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown server gracefully
|
||||
func (f *Fiber) Shutdown() error {
|
||||
if f.httpServer == nil {
|
||||
func (app *Application) Shutdown() error {
|
||||
if app.httpServer == nil {
|
||||
return fmt.Errorf("Server is not running")
|
||||
}
|
||||
return f.httpServer.Shutdown()
|
||||
return app.httpServer.Shutdown()
|
||||
}
|
||||
|
||||
// Test takes a http.Request and execute a fake connection to the application
|
||||
// It returns a http.Response when the connection was successfull
|
||||
func (app *Application) Test(req *http.Request) (*http.Response, error) {
|
||||
// Get raw http request
|
||||
reqRaw, err := httputil.DumpRequest(req, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Setup a fiber server struct
|
||||
app.httpServer = app.setupServer()
|
||||
// Create fake connection
|
||||
conn := &conn{}
|
||||
// Pass HTTP request to conn
|
||||
_, err = conn.r.Write(reqRaw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Serve conn to server
|
||||
channel := make(chan error)
|
||||
go func() {
|
||||
channel <- app.httpServer.ServeConn(conn)
|
||||
}()
|
||||
// Wait for callback
|
||||
select {
|
||||
case err := <-channel:
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Throw timeout error after 200ms
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
return nil, fmt.Errorf("Timeout")
|
||||
}
|
||||
// Get raw HTTP response
|
||||
respRaw, err := ioutil.ReadAll(&conn.w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Create buffer
|
||||
reader := strings.NewReader(getString(respRaw))
|
||||
buffer := bufio.NewReader(reader)
|
||||
// Convert raw HTTP response to http.Response
|
||||
resp, err := http.ReadResponse(buffer, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Return *http.Response
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
func (f *Fiber) prefork(host string, tls ...string) {
|
||||
func (app *Application) prefork(host string, tls ...string) {
|
||||
// Master proc
|
||||
if !f.child {
|
||||
if !app.child {
|
||||
// Create babies
|
||||
childs := make([]*exec.Cmd, runtime.NumCPU())
|
||||
|
||||
|
@ -431,38 +478,38 @@ func (f *Fiber) prefork(host string, tls ...string) {
|
|||
|
||||
// enable TLS/HTTPS
|
||||
if len(tls) > 1 {
|
||||
if err := f.httpServer.ServeTLS(ln, tls[0], tls[1]); err != nil {
|
||||
if err := app.httpServer.ServeTLS(ln, tls[0], tls[1]); err != nil {
|
||||
log.Fatal("Listen-prefork: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := f.httpServer.Serve(ln); err != nil {
|
||||
if err := app.httpServer.Serve(ln); err != nil {
|
||||
log.Fatal("Listen-prefork: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Fiber) setupServer() *fasthttp.Server {
|
||||
func (app *Application) setupServer() *fasthttp.Server {
|
||||
return &fasthttp.Server{
|
||||
Handler: f.handler,
|
||||
Name: f.Server,
|
||||
Concurrency: f.Engine.Concurrency,
|
||||
DisableKeepalive: f.Engine.DisableKeepAlive,
|
||||
ReadBufferSize: f.Engine.ReadBufferSize,
|
||||
WriteBufferSize: f.Engine.WriteBufferSize,
|
||||
ReadTimeout: f.Engine.ReadTimeout,
|
||||
WriteTimeout: f.Engine.WriteTimeout,
|
||||
IdleTimeout: f.Engine.IdleTimeout,
|
||||
MaxConnsPerIP: f.Engine.MaxConnsPerIP,
|
||||
MaxRequestsPerConn: f.Engine.MaxRequestsPerConn,
|
||||
TCPKeepalive: f.Engine.TCPKeepalive,
|
||||
TCPKeepalivePeriod: f.Engine.TCPKeepalivePeriod,
|
||||
MaxRequestBodySize: f.Engine.MaxRequestBodySize,
|
||||
ReduceMemoryUsage: f.Engine.ReduceMemoryUsage,
|
||||
GetOnly: f.Engine.GetOnly,
|
||||
DisableHeaderNamesNormalizing: f.Engine.DisableHeaderNamesNormalizing,
|
||||
SleepWhenConcurrencyLimitsExceeded: f.Engine.SleepWhenConcurrencyLimitsExceeded,
|
||||
NoDefaultServerHeader: f.Server == "",
|
||||
NoDefaultContentType: f.Engine.NoDefaultContentType,
|
||||
KeepHijackedConns: f.Engine.KeepHijackedConns,
|
||||
Handler: app.handler,
|
||||
Name: app.Server,
|
||||
Concurrency: app.Engine.Concurrency,
|
||||
DisableKeepalive: app.Engine.DisableKeepAlive,
|
||||
ReadBufferSize: app.Engine.ReadBufferSize,
|
||||
WriteBufferSize: app.Engine.WriteBufferSize,
|
||||
ReadTimeout: app.Engine.ReadTimeout,
|
||||
WriteTimeout: app.Engine.WriteTimeout,
|
||||
IdleTimeout: app.Engine.IdleTimeout,
|
||||
MaxConnsPerIP: app.Engine.MaxConnsPerIP,
|
||||
MaxRequestsPerConn: app.Engine.MaxRequestsPerConn,
|
||||
TCPKeepalive: app.Engine.TCPKeepalive,
|
||||
TCPKeepalivePeriod: app.Engine.TCPKeepalivePeriod,
|
||||
MaxRequestBodySize: app.Engine.MaxRequestBodySize,
|
||||
ReduceMemoryUsage: app.Engine.ReduceMemoryUsage,
|
||||
GetOnly: app.Engine.GetOnly,
|
||||
DisableHeaderNamesNormalizing: app.Engine.DisableHeaderNamesNormalizing,
|
||||
SleepWhenConcurrencyLimitsExceeded: app.Engine.SleepWhenConcurrencyLimitsExceeded,
|
||||
NoDefaultServerHeader: app.Server == "",
|
||||
NoDefaultContentType: app.Engine.NoDefaultContentType,
|
||||
KeepHijackedConns: app.Engine.KeepHijackedConns,
|
||||
}
|
||||
}
|
||||
|
|
2
go.mod
2
go.mod
|
@ -3,7 +3,7 @@ module github.com/gofiber/fiber
|
|||
go 1.11
|
||||
|
||||
require (
|
||||
github.com/fatih/color v1.9.0
|
||||
github.com/json-iterator/go v1.1.9
|
||||
github.com/mattn/go-colorable v0.1.4
|
||||
github.com/valyala/fasthttp v1.9.0
|
||||
)
|
||||
|
|
6
go.sum
6
go.sum
|
@ -1,5 +1,6 @@
|
|||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
|
@ -7,10 +8,9 @@ github.com/klauspost/compress v1.8.2 h1:Bx0qjetmNjdFXASH02NSAREKpiaDwkO1DRZ3dV2K
|
|||
github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
|
||||
github.com/klauspost/cpuid v1.2.1 h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=
|
||||
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
|
||||
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
|
||||
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||
|
@ -27,6 +27,6 @@ github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV
|
|||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
|
22
router.go
22
router.go
|
@ -17,7 +17,7 @@ import (
|
|||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// Ctx : struct
|
||||
// Ctx is the context that contains everything
|
||||
type Ctx struct {
|
||||
route *Route
|
||||
next bool
|
||||
|
@ -26,7 +26,7 @@ type Ctx struct {
|
|||
Fasthttp *fasthttp.RequestCtx
|
||||
}
|
||||
|
||||
// Route : struct
|
||||
// Route struct
|
||||
type Route struct {
|
||||
// HTTP method in uppercase, can be a * for Use() & All()
|
||||
Method string
|
||||
|
@ -68,8 +68,8 @@ func releaseCtx(ctx *Ctx) {
|
|||
poolCtx.Put(ctx)
|
||||
}
|
||||
|
||||
func (g *Group) register(method string, args ...interface{}) {
|
||||
path := g.path
|
||||
func (grp *Group) register(method string, args ...interface{}) {
|
||||
path := grp.path
|
||||
var handler func(*Ctx)
|
||||
if len(args) == 1 {
|
||||
handler = args[0].(func(*Ctx))
|
||||
|
@ -82,11 +82,11 @@ func (g *Group) register(method string, args ...interface{}) {
|
|||
path = strings.Replace(path, "//", "/", -1)
|
||||
path = filepath.Clean(path)
|
||||
}
|
||||
g.fiber.register(method, path, handler)
|
||||
grp.app.register(method, path, handler)
|
||||
}
|
||||
|
||||
// Function to add a route correctly
|
||||
func (f *Fiber) register(method string, args ...interface{}) {
|
||||
func (app *Application) register(method string, args ...interface{}) {
|
||||
// Set if method is Use() midware
|
||||
var midware = method == "USE"
|
||||
|
||||
|
@ -121,7 +121,7 @@ func (f *Fiber) register(method string, args ...interface{}) {
|
|||
|
||||
// If the route needs to match any path
|
||||
if path == "" || path == "*" || path == "/*" {
|
||||
f.routes = append(f.routes, &Route{method, path, midware, true, nil, nil, handler})
|
||||
app.routes = append(app.routes, &Route{method, path, midware, true, nil, nil, handler})
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -130,7 +130,7 @@ func (f *Fiber) register(method string, args ...interface{}) {
|
|||
|
||||
// If path has no params (simple path), we don't need regex (also for use())
|
||||
if midware || len(params) == 0 {
|
||||
f.routes = append(f.routes, &Route{method, path, midware, false, nil, nil, handler})
|
||||
app.routes = append(app.routes, &Route{method, path, midware, false, nil, nil, handler})
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -141,11 +141,11 @@ func (f *Fiber) register(method string, args ...interface{}) {
|
|||
}
|
||||
|
||||
// Add regex + params to route
|
||||
f.routes = append(f.routes, &Route{method, path, midware, false, regex, params, handler})
|
||||
app.routes = append(app.routes, &Route{method, path, midware, false, regex, params, handler})
|
||||
}
|
||||
|
||||
// then try to match a route as efficient as possible.
|
||||
func (f *Fiber) handler(fctx *fasthttp.RequestCtx) {
|
||||
func (app *Application) handler(fctx *fasthttp.RequestCtx) {
|
||||
found := false
|
||||
|
||||
// get custom context from sync pool
|
||||
|
@ -156,7 +156,7 @@ func (f *Fiber) handler(fctx *fasthttp.RequestCtx) {
|
|||
method := ctx.Method()
|
||||
|
||||
// loop trough routes
|
||||
for _, route := range f.routes {
|
||||
for _, route := range app.routes {
|
||||
// Skip route if method is not allowed
|
||||
if route.Method != "*" && route.Method != method {
|
||||
continue
|
||||
|
|
56
utils.go
56
utils.go
|
@ -8,13 +8,9 @@
|
|||
package fiber
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
|
@ -111,56 +107,20 @@ func getBytes(s string) (b []byte) {
|
|||
return b
|
||||
}
|
||||
|
||||
// Test takes a http.Request and execute a fake connection to the application
|
||||
// It returns a http.Response when the connection was successfull
|
||||
func (f *Fiber) Test(req *http.Request) (*http.Response, error) {
|
||||
// Get raw http request
|
||||
reqRaw, err := httputil.DumpRequest(req, true)
|
||||
// Check for error and format
|
||||
func checkErr(err error, title ...string) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Setup a fiber server struct
|
||||
f.httpServer = f.setupServer()
|
||||
// Create fake connection
|
||||
conn := &conn{}
|
||||
// Pass HTTP request to conn
|
||||
_, err = conn.r.Write(reqRaw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Serve conn to server
|
||||
channel := make(chan error)
|
||||
go func() {
|
||||
channel <- f.httpServer.ServeConn(conn)
|
||||
}()
|
||||
// Wait for callback
|
||||
select {
|
||||
case err := <-channel:
|
||||
if err != nil {
|
||||
return nil, err
|
||||
t := "Error"
|
||||
if len(title) > 0 {
|
||||
t = title[0]
|
||||
}
|
||||
// Throw timeout error after 200ms
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
return nil, fmt.Errorf("Timeout")
|
||||
fmt.Printf("\n%s%s: %v%s\n\n", "\x1b[1;30m", t, err, "\x1b[0m")
|
||||
os.Exit(1)
|
||||
}
|
||||
// Get raw HTTP response
|
||||
respRaw, err := ioutil.ReadAll(&conn.w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Create buffer
|
||||
reader := strings.NewReader(getString(respRaw))
|
||||
buffer := bufio.NewReader(reader)
|
||||
// Convert raw HTTP response to http.Response
|
||||
resp, err := http.ReadResponse(buffer, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Return *http.Response
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// https://golang.org/src/net/net.go#L113
|
||||
// Helper methods for Testing
|
||||
type conn struct {
|
||||
net.Conn
|
||||
r bytes.Buffer
|
||||
|
|
Loading…
Reference in New Issue