mirror of https://github.com/gofiber/fiber.git
Update README.md
parent
57755c1e4b
commit
ed2122d586
286
docs/README.md
286
docs/README.md
|
@ -9,13 +9,13 @@ docsify serve ./docs
|
|||
[](https://github.com/fenny/fiber/blob/master/LICENSE)
|
||||
[](https://gitter.im/FiberGo/community)
|
||||
<br><br>
|
||||
**Fiber** is a router framework build on top of [FastHTTP](https://github.com/valyala/fasthttp), the fastest HTTP package for **Go**.<br>
|
||||
This library is inspired by [Expressjs](https://github.com/expressjs/fiber), one of the most populair and well known web framework for **Nodejs**.
|
||||
**[Fiber](https://github.com/fenny/fiber)** is a router framework build on top of [FastHTTP](https://github.com/valyala/fasthttp), the fastest HTTP package for **[Go](https://golang.org/doc/)**.<br>
|
||||
This library is inspired by [Express](https://expressjs.com/en/4x/api.html), one of the most populair and well known web framework for **[Nodejs](https://nodejs.org/en/about/)**.
|
||||
|
||||
### Getting started
|
||||
|
||||
#### Installing
|
||||
Assuming you’ve already installed Golang, install the Fiber package by calling the following command:
|
||||
Assuming you’ve already installed [Go](https://golang.org/doc/), install the [Fiber](https://github.com/fenny/fiber) package by calling the following command:
|
||||
```shell
|
||||
$ go get -u github.com/fenny/fiber
|
||||
```
|
||||
|
@ -52,87 +52,83 @@ Each route can have one handler function, that is executed when the route is mat
|
|||
Route definition takes the following structures:
|
||||
|
||||
```go
|
||||
app.Method(handler)
|
||||
app.Method(path, handler)
|
||||
// Function signature
|
||||
app.Method(func(*fiber.Ctx))
|
||||
app.Method(path string, func(*fiber.Ctx))
|
||||
app.Method(static string)
|
||||
app.Method(path string, static string)
|
||||
```
|
||||
|
||||
* **app** is an instance of **fiber**.
|
||||
* **app** is an instance of **[Fiber](#hello-world)**.
|
||||
* **Method** is an [HTTP request method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods), in capitalization: Get, Put, Post etc
|
||||
* **path** is a path on the server.
|
||||
* **handler** is a function executed when the route is matched.
|
||||
* **path string** is a path or prefix (for static files) on the server.
|
||||
* **static string** is a file path or directory.
|
||||
* **func(*fiber.Ctx)** is a function executed when the route is matched.
|
||||
|
||||
This tutorial assumes that an instance of fiber named app is created and the server is running. If you are not familiar with creating an app and starting it, see the [Hello world](#hello-world) example.
|
||||
|
||||
The following examples illustrate defining simple routes.
|
||||
Respond with Hello, World! on the homepage:
|
||||
```go
|
||||
// Respond with Hello, World! on the homepage:
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
||||
Respond to POST request on the root route (/), the application’s home page:
|
||||
```go
|
||||
//Respond to POST request on the root route (/), the application’s home page:
|
||||
app.Post("/", func(c *fiber.Ctx) {
|
||||
c.Send("Got a POST request")
|
||||
})
|
||||
```
|
||||
|
||||
Respond to a PUT request to the /user route:
|
||||
```go
|
||||
// Respond to a PUT request to the /user route:
|
||||
app.Put("/user", func(c *fiber.Ctx) {
|
||||
c.Send("Got a PUT request at /user")
|
||||
})
|
||||
```
|
||||
|
||||
Respond to a DELETE request to the /user route:
|
||||
```go
|
||||
// Respond to a DELETE request to the /user route:
|
||||
app.Delete("/user", func(c *fiber.Ctx) {
|
||||
c.Send("Got a DELETE request at /user")
|
||||
})
|
||||
```
|
||||
|
||||
#### Static files
|
||||
To serve static files such as images, CSS files, and JavaScript files, replace your function handler with a file or directory string.
|
||||
```go
|
||||
// Function signature
|
||||
app.Method(static string)
|
||||
app.Method(path string, static string)
|
||||
```
|
||||
|
||||
To serve static files such as images, CSS files, and JavaScript files, replace your function handler with a file or directory string.
|
||||
|
||||
The function signature is:
|
||||
```go
|
||||
app.Method(static)
|
||||
app.Method(path, static)
|
||||
```
|
||||
The root argument specifies the root directory from which to serve static assets.
|
||||
You can also specify a single file instead of a directory, for example:
|
||||
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
|
||||
|
||||
```go
|
||||
app.Get("./public")
|
||||
// http://localhost:8080/images/kitten.jpg
|
||||
// http://localhost:8080/css/style.css
|
||||
// http://localhost:8080/js/app.js
|
||||
// http://localhost:8080/images/bg.png
|
||||
// http://localhost:8080/hello.html
|
||||
app.Get("/static", "./public")
|
||||
// http://localhost:8080/static/images/kitten.jpg
|
||||
// http://localhost:8080/static/css/style.css
|
||||
// etc
|
||||
app.Get("/specific/path", "./public/index.html")
|
||||
// http://localhost:8080/specific/path
|
||||
// => ./public/index.html
|
||||
app.Get("*", "./public/index.html")
|
||||
// http://localhost:8080/my/name/is/jeff
|
||||
// => ./public/index.html
|
||||
|
||||
```
|
||||
Fiber looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
|
||||
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the fiber.Static function, specify a mount path for the static directory, as shown below:
|
||||
Now, you can load the files that are in the public directory:
|
||||
```shell
|
||||
http://localhost:8080/images/kitten.jpg
|
||||
http://localhost:8080/css/style.css
|
||||
http://localhost:8080/js/app.js
|
||||
http://localhost:8080/images/bg.png
|
||||
http://localhost:8080/hello.html
|
||||
```
|
||||
To use multiple static assets directories, call the express.static middleware function multiple times:
|
||||
```go
|
||||
app.Get("/css", "./build/css/minified")
|
||||
app.Get("./public")
|
||||
app.Get("./files")
|
||||
```
|
||||
?>For best results, use a reverse proxy cache like [NGINX](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) to improve performance of serving static assets.
|
||||
|
||||
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
|
||||
```go
|
||||
app.Get("/static", "./public")
|
||||
```
|
||||
Now, you can load the files that are in the public directory from the /static path prefix.
|
||||
```shell
|
||||
http://localhost:8080/static/images/kitten.jpg
|
||||
http://localhost:8080/static/css/style.css
|
||||
http://localhost:8080/static/js/app.js
|
||||
http://localhost:8080/static/images/bg.png
|
||||
http://localhost:8080/static/hello.html
|
||||
```
|
||||
|
||||
### Application
|
||||
The app object conventionally denotes the Fiber application.
|
||||
|
@ -153,47 +149,142 @@ app := fiber.New()
|
|||
app.TLSEnable = false,
|
||||
app.CertKey = ""
|
||||
app.CertFile = ""
|
||||
|
||||
// Server name for sending in response headers.
|
||||
//
|
||||
// No server header is send if left empty.
|
||||
|
||||
app.Name = ""
|
||||
// The maximum number of concurrent connections the server may serve.
|
||||
|
||||
app.Concurrency = 256 * 1024
|
||||
|
||||
// Whether to disable keep-alive connections.
|
||||
//
|
||||
// The server will close all the incoming connections after sending
|
||||
// the first response to client if this option is set to true.
|
||||
//
|
||||
// By default keep-alive connections are enabled.
|
||||
app.DisableKeepAlive = false
|
||||
|
||||
// Per-connection buffer size for requests' reading.
|
||||
// This also limits the maximum header size.
|
||||
//
|
||||
// Increase this buffer if your clients send multi-KB RequestURIs
|
||||
// and/or multi-KB headers (for example, BIG cookies).
|
||||
app.ReadBufferSize = 4096
|
||||
|
||||
// Per-connection buffer size for responses' writing.
|
||||
app.WriteBufferSize = 4096
|
||||
|
||||
// WriteTimeout is the maximum duration before timing out
|
||||
// writes of the response. It is reset after the request handler
|
||||
// has returned.
|
||||
//
|
||||
// By default response write timeout is unlimited.
|
||||
app.WriteTimeout = 0
|
||||
|
||||
// IdleTimeout is the maximum amount of time to wait for the
|
||||
// next request when keep-alive is enabled. If IdleTimeout
|
||||
// is zero, the value of ReadTimeout is used.
|
||||
app.IdleTimeout = 0
|
||||
|
||||
// Maximum number of concurrent client connections allowed per IP.
|
||||
//
|
||||
// By default unlimited number of concurrent connections
|
||||
// may be established to the server from a single IP address.
|
||||
app.MaxConnsPerIP = 0
|
||||
|
||||
// Maximum number of requests served per connection.
|
||||
//
|
||||
// The server closes connection after the last request.
|
||||
// 'Connection: close' header is added to the last response.
|
||||
//
|
||||
// By default unlimited number of requests may be served per connection.
|
||||
app.MaxRequestsPerConn = 0
|
||||
|
||||
// Whether to enable tcp keep-alive connections.
|
||||
//
|
||||
// Whether the operating system should send tcp keep-alive messages on the tcp connection.
|
||||
//
|
||||
// By default tcp keep-alive connections are disabled.
|
||||
app.TCPKeepalive = false
|
||||
|
||||
// Period between tcp keep-alive messages.
|
||||
//
|
||||
// TCP keep-alive period is determined by operation system by default.
|
||||
app.TCPKeepalivePeriod = 0
|
||||
|
||||
// Maximum request body size.
|
||||
//
|
||||
// The server rejects requests with bodies exceeding this limit.
|
||||
//
|
||||
// Request body size is limited by DefaultMaxRequestBodySize by default.
|
||||
app.MaxRequestBodySize = 4 * 1024 * 1024
|
||||
|
||||
// Aggressively reduces memory usage at the cost of higher CPU usage
|
||||
// if set to true.
|
||||
//
|
||||
// Try enabling this option only if the server consumes too much memory
|
||||
// serving mostly idle keep-alive connections. This may reduce memory
|
||||
// usage by more than 50%.
|
||||
//
|
||||
// Aggressive memory usage reduction is disabled by default.
|
||||
app.ReduceMemoryUsage = false
|
||||
|
||||
// Rejects all non-GET requests if set to true.
|
||||
//
|
||||
// This option is useful as anti-DoS protection for servers
|
||||
// accepting only GET requests. The request size is limited
|
||||
// by ReadBufferSize if GetOnly is set.
|
||||
//
|
||||
// Server accepts all the requests by default.
|
||||
app.GetOnly = false
|
||||
|
||||
// By default request and response header names are normalized, i.e.
|
||||
// The first letter and the first letters following dashes
|
||||
// are uppercased, while all the other letters are lowercased.
|
||||
// Examples:
|
||||
//
|
||||
// * HOST -> Host
|
||||
// * content-type -> Content-Type
|
||||
// * cONTENT-lenGTH -> Content-Length
|
||||
app.DisableHeaderNamesNormalizing = false
|
||||
|
||||
// SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if
|
||||
// the concurrency limit in exceeded (default [when is 0]: don't sleep
|
||||
// and accept new connections immidiatelly).
|
||||
app.SleepWhenConcurrencyLimitsExceeded = 0
|
||||
app.NoDefaultServerHeader = true
|
||||
|
||||
// NoDefaultContentType, when set to true, causes the default Content-Type
|
||||
// header to be excluded from the Response.
|
||||
//
|
||||
// The default Content-Type header value is the internal default value. When
|
||||
// set to true, the Content-Type will not be present.
|
||||
app.NoDefaultContentType = false
|
||||
KeepHijackedConns = false
|
||||
|
||||
// KeepHijackedConns is an opt-in disable of connection
|
||||
// close by fasthttp after connections' HijackHandler returns.
|
||||
// This allows to save goroutines, e.g. when fasthttp used to upgrade
|
||||
// http connections to WS and connection goes to another handler,
|
||||
// which will close it when needed.
|
||||
app.KeepHijackedConns = false
|
||||
```
|
||||
#### Methods
|
||||
Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on. See Routing methods below for the complete list.
|
||||
Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on capitalized. Thus, the actual methods are app.Get(), app.Post(), app.Put(), and so on. See Routing methods below for the complete list.
|
||||
```go
|
||||
// Function signature
|
||||
app.Method(static string)
|
||||
app.Method(func(*fiber.Ctx))
|
||||
app.Method(path string, static string)
|
||||
app.Method(path string, func(*fiber.Ctx))
|
||||
|
||||
// Example
|
||||
app.Connect("/", handler)
|
||||
app.Delete("/", handler)
|
||||
app.Get("/", handler)
|
||||
app.Head("/", handler)
|
||||
app.Options("/", handler)
|
||||
app.Patch("/", handler)
|
||||
app.Post("/", handler)
|
||||
app.Put("/", handler)
|
||||
app.Trace("/", handler)
|
||||
app.Connect(...)
|
||||
app.Delete(...)
|
||||
app.Get(...)
|
||||
app.Head(...)
|
||||
app.Options(...)
|
||||
app.Patch(...)
|
||||
app.Post(...)
|
||||
app.Put(...)
|
||||
app.Trace(...)
|
||||
// Matches all HTTP verbs
|
||||
app.All("/", handler)
|
||||
app.All(...)
|
||||
```
|
||||
#### Listen
|
||||
Binds and listens for connections on the specified host and port.
|
||||
|
@ -256,14 +347,47 @@ app.Get("/ab(cd)?e", func(c *fiber.Ctx) {
|
|||
|
||||
|
||||
#### Parameters
|
||||
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
|
||||
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values can be retrieved using the [Params()](#params) function, with the name of the route parameter specified in the path as their respective keys.
|
||||
|
||||
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
|
||||
|
||||
```go
|
||||
app.Get("/user/:name/books/:title", func(c *fiber.Ctx) {
|
||||
c.Write(c.Params("name"))
|
||||
c.Write(c.Params("title"))
|
||||
})
|
||||
|
||||
app.Get("/user/*", func(c *fiber.Ctx) {
|
||||
c.Send(c.Params("*"))
|
||||
})
|
||||
|
||||
app.Get("/user/:name?", func(c *fiber.Ctx) {
|
||||
c.Send(c.Params("name"))
|
||||
})
|
||||
```
|
||||
?>The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).
|
||||
|
||||
!> The hyphen (-) and the dot (.) are not interpreted literally yet, planned for V2
|
||||
|
||||
#### Middleware
|
||||
You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
|
||||
The [Next()](#next) function is a function in the [Fiber](https://github.com/fenny/fiber) router which, when called, executes the next function that matches the current route.
|
||||
|
||||
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
|
||||
Functions that are designed to make changes to the request or response are called middleware functions.
|
||||
|
||||
Here is a simple example of a middleware function that prints "ip > path" when a request to the app passes through it.
|
||||
|
||||
```go
|
||||
app := fiber.New()
|
||||
app.Get(func(c *fiber.Ctx) {
|
||||
fmt.Println(c.IP(), "=>", c.Path())
|
||||
c.Next()
|
||||
})
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send("Hello, World!")
|
||||
})
|
||||
app.Listen(8080)
|
||||
```
|
||||
|
||||
A single callback function can handle a route. For example:
|
||||
### Context
|
||||
The ctx object represents the HTTP request and response and has methods for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the context is always referred to as c but its actual name is determined by the parameters to the callback function in which you’re working.
|
||||
|
||||
|
@ -458,6 +582,28 @@ app.Post("/", func(c *fiber.Ctx) {
|
|||
// => "POST"
|
||||
})
|
||||
```
|
||||
|
||||
#### Next
|
||||
When Next() is called, it executes the next function in the stack that matches the current route.
|
||||
```go
|
||||
// Function signature
|
||||
c.Next()
|
||||
|
||||
// Example
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
fmt.Printl("1st route!")
|
||||
c.Next()
|
||||
})
|
||||
app.Get("*", func(c *fiber.Ctx) {
|
||||
fmt.Printl("2nd route!")
|
||||
c.Next()
|
||||
})
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
fmt.Printl("3rd route!")
|
||||
c.Send("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
||||
#### OriginalURL
|
||||
Contains the original request URL.
|
||||
```go
|
||||
|
|
Loading…
Reference in New Issue