From 695517b33079c78e928651e37a4ee07560f59578 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Thu, 28 Mar 2024 09:59:47 +0100 Subject: [PATCH 1/3] [v3-Maintenance]-Consolidate-and-Document-Core-Changes-in-v3 --- docs/core/api/app.md | 229 +++++++++++----------------- docs/core/api/fiber.md | 254 ++++++++++++++++++++++++-------- docs/core/extra/_category_.json | 2 +- docs/core/guide/routing.md | 4 +- docs/core/intro.md | 2 +- docs/core/whats_new.md | 29 ++++ sidebars.js | 3 +- 7 files changed, 317 insertions(+), 206 deletions(-) create mode 100644 docs/core/whats_new.md diff --git a/docs/core/api/app.md b/docs/core/api/app.md index d44944f7ddb..aa9e5e90c4e 100644 --- a/docs/core/api/app.md +++ b/docs/core/api/app.md @@ -5,9 +5,11 @@ description: The app instance conventionally denotes the Fiber application. sidebar_position: 2 --- +## Routing + import RoutingHandler from './../partials/routing/handler.md'; -## Static +### Static Use the **Static** method to serve static files such as **images**, **CSS,** and **JavaScript**. @@ -109,11 +111,11 @@ app.Static("/", "./public", fiber.Static{ }) ``` -## Route Handlers +### Route Handlers -## Mount +### Mount You can Mount Fiber instance by creating a `*Mount` @@ -135,7 +137,7 @@ func main() { } ``` -## MountPath +### MountPath The `MountPath` property contains one or more path patterns on which a sub-app was mounted. @@ -165,7 +167,7 @@ func main() { Mounting order is important for MountPath. If you want to get mount paths properly, you should start mounting from the deepest app. ::: -## Group +### Group You can group routes by creating a `*Group` struct. @@ -191,7 +193,7 @@ func main() { } ``` -## Route +### Route You can define routes with a common prefix inside the common function. @@ -212,39 +214,7 @@ func main() { } ``` -## Server - -Server returns the underlying [fasthttp server](https://godoc.org/github.com/valyala/fasthttp#Server) - -```go title="Signature" -func (app *App) Server() *fasthttp.Server -``` - -```go title="Examples" -func main() { - app := fiber.New() - - app.Server().MaxConnsPerIP = 1 - - // ... -} -``` - -## Server Shutdown - -Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waits indefinitely for all connections to return to idle before shutting down. - -ShutdownWithTimeout will forcefully close any active connections after the timeout expires. - -ShutdownWithContext shuts down the server including by force if the context's deadline is exceeded. - -```go -func (app *App) Shutdown() error -func (app *App) ShutdownWithTimeout(timeout time.Duration) error -func (app *App) ShutdownWithContext(ctx context.Context) error -``` - -## HandlersCount +### HandlersCount This method returns the amount of registered handlers. @@ -252,7 +222,7 @@ This method returns the amount of registered handlers. func (app *App) HandlersCount() uint32 ``` -## Stack +### Stack This method returns the original router stack @@ -306,7 +276,7 @@ func main() { ] ``` -## Name +### Name This method assigns the name of latest created route. @@ -408,7 +378,7 @@ func main() { ] ``` -## GetRoute +### GetRoute This method gets the route by name. @@ -429,7 +399,6 @@ func main() { app.Listen(":3000") - } ``` @@ -442,7 +411,7 @@ func main() { } ``` -## GetRoutes +### GetRoutes This method gets all routes. @@ -489,144 +458,118 @@ Handler returns the server handler that can be used to serve custom \*fasthttp.R func (app *App) Handler() fasthttp.RequestHandler ``` -## Listen +## ErrorHandler -Listen serves HTTP requests from the given address. +Errorhandler executes the process which was defined for the application in case of errors, this is used in some cases in middlewares. ```go title="Signature" -func (app *App) Listen(addr string) error -``` - -```go title="Examples" -// Listen on port :8080 -app.Listen(":8080") - -// Custom host -app.Listen("127.0.0.1:8080") +func (app *App) ErrorHandler(ctx Ctx, err error) error ``` -## ListenTLS +## NewCtxFunc -ListenTLS serves HTTPs requests from the given address using certFile and keyFile paths to as TLS certificate and key file. +NewCtxFunc allows to customize the ctx struct as we want. ```go title="Signature" -func (app *App) ListenTLS(addr, certFile, keyFile string) error +func (app *App) NewCtxFunc(function func(app *App) CustomCtx) ``` ```go title="Examples" -app.ListenTLS(":443", "./cert.pem", "./cert.key"); -``` - -Using `ListenTLS` defaults to the following config \( use `Listener` to provide your own config \) - -```go title="Default \*tls.Config" -&tls.Config{ - MinVersion: tls.VersionTLS12, - Certificates: []tls.Certificate{ - cert, - }, +type CustomCtx struct { + DefaultCtx } -``` - -## ListenTLSWithCertificate - -```go title="Signature" -func (app *App) ListenTLS(addr string, cert tls.Certificate) error -``` - -```go title="Examples" -app.ListenTLSWithCertificate(":443", cert); -``` -Using `ListenTLSWithCertificate` defaults to the following config \( use `Listener` to provide your own config \) - -```go title="Default \*tls.Config" -&tls.Config{ - MinVersion: tls.VersionTLS12, - Certificates: []tls.Certificate{ - cert, - }, +// Custom method +func (c *CustomCtx) Params(key string, defaultValue ...string) string { + return "prefix_" + c.DefaultCtx.Params(key) } -``` - -## ListenMutualTLS - -ListenMutualTLS serves HTTPs requests from the given address using certFile, keyFile and clientCertFile are the paths to TLS certificate and key file - -```go title="Signature" -func (app *App) ListenMutualTLS(addr, certFile, keyFile, clientCertFile string) error -``` - -```go title="Examples" -app.ListenMutualTLS(":443", "./cert.pem", "./cert.key", "./ca-chain-cert.pem"); -``` - -Using `ListenMutualTLS` defaults to the following config \( use `Listener` to provide your own config \) -```go title="Default \*tls.Config" -&tls.Config{ - MinVersion: tls.VersionTLS12, - ClientAuth: tls.RequireAndVerifyClientCert, - ClientCAs: clientCertPool, - Certificates: []tls.Certificate{ - cert, - }, -} +app := New() +app.NewCtxFunc(func(app *fiber.App) fiber.CustomCtx { + return &CustomCtx{ + DefaultCtx: *NewDefaultCtx(app), + } +}) +// curl http://localhost:3000/123 +app.Get("/:id", func(c Ctx) error { + // use custom method - output: prefix_123 + return c.SendString(c.Params("id")) +}) ``` -## ListenMutualTLSWithCertificate +## RegisterCustomBinder -ListenMutualTLSWithCertificate serves HTTPs requests from the given address using certFile, keyFile and clientCertFile are the paths to TLS certificate and key file +You can register custom binders to use as Bind().Custom("name"). +They should be compatible with CustomBinder interface. ```go title="Signature" -func (app *App) ListenMutualTLSWithCertificate(addr string, cert tls.Certificate, clientCertPool *x509.CertPool) error +func (app *App) RegisterCustomBinder(binder CustomBinder) ``` ```go title="Examples" -app.ListenMutualTLSWithCertificate(":443", cert, clientCertPool); -``` - -Using `ListenMutualTLSWithCertificate` defaults to the following config \( use `Listener` to provide your own config \) +app := fiber.New() -```go title="Default \*tls.Config" -&tls.Config{ - MinVersion: tls.VersionTLS12, - ClientAuth: tls.RequireAndVerifyClientCert, - ClientCAs: clientCertPool, - Certificates: []tls.Certificate{ - cert, - }, +// My custom binder +customBinder := &customBinder{} +// Name of custom binder, which will be used as Bind().Custom("name") +func (*customBinder) Name() string { + return "custom" +} +// Is used in the Body Bind method to check if the binder should be used for custom mime types +func (*customBinder) MIMETypes() []string { + return []string{"application/yaml"} +} +// Parse the body and bind it to the out interface +func (*customBinder) Parse(c Ctx, out any) error { + // parse yaml body + return yaml.Unmarshal(c.Body(), out) } +// Register custom binder +app.RegisterCustomBinder(customBinder) + +// curl -X POST http://localhost:3000/custom -H "Content-Type: application/yaml" -d "name: John" +app.Post("/custom", func(c Ctx) error { + var user User + // output: {Name:John} + // Custom binder is used by the name + if err := c.Bind().Custom("custom", &user); err != nil { + return err + } + // ... + return c.JSON(user) +}) +// curl -X POST http://localhost:3000/normal -H "Content-Type: application/yaml" -d "name: Doe" +app.Post("/normal", func(c Ctx) error { + var user User + // output: {Name:Doe} + // Custom binder is used by the mime type + if err := c.Bind().Body(&user); err != nil { + return err + } + // ... + return c.JSON(user) +}) ``` -## Listener +## RegisterCustomConstraint -You can pass your own [`net.Listener`](https://pkg.go.dev/net/#Listener) using the `Listener` method. This method can be used to enable **TLS/HTTPS** with a custom tls.Config. +RegisterCustomConstraint allows to register custom constraint. ```go title="Signature" -func (app *App) Listener(ln net.Listener) error +func (app *App) RegisterCustomConstraint(constraint CustomConstraint) ``` -```go title="Examples" -ln, _ := net.Listen("tcp", ":3000") +See [Custom Constraint](../guide/routing.md#custom-constraint) section for more information. -cer, _:= tls.LoadX509KeyPair("server.crt", "server.key") -ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cer}}) +## SetTLSHandler -app.Listener(ln) -``` - -## RegisterCustomConstraint - -RegisterCustomConstraint allows to register custom constraint. +Use SetTLSHandler to set [ClientHelloInfo](https://datatracker.ietf.org/doc/html/rfc8446#section-4.1.2) when using TLS with Listener. ```go title="Signature" -func (app *App) RegisterCustomConstraint(constraint CustomConstraint) +func (app *App) SetTLSHandler(tlsHandler *TLSHandler) ``` -See [Custom Constraint](../guide/routing.md#custom-constraint) section for more information. - ## Test Testing your application is done with the **Test** method. Use this method for creating `_test.go` files or when you need to debug your routing logic. The default timeout is `1s` if you want to disable a timeout altogether, pass `-1` as a second argument. diff --git a/docs/core/api/fiber.md b/docs/core/api/fiber.md index 05fd4941e8d..d3d89914409 100644 --- a/docs/core/api/fiber.md +++ b/docs/core/api/fiber.md @@ -5,9 +5,11 @@ description: Fiber represents the fiber package where you start to create an ins sidebar_position: 1 --- -## New +## Server start -This method creates a new **App** named instance. You can pass optional [config ](#config)when creating a new instance. +### New + +This method creates a new **App** named instance. You can pass optional [config](#config)when creating a new instance. ```go title="Signature" func New(config ...Config) *App @@ -20,14 +22,13 @@ app := fiber.New() // ... ``` -## Config +### Config You can pass an optional Config when creating a new Fiber instance. ```go title="Example" // Custom config app := fiber.New(fiber.Config{ - Prefork: true, CaseSensitive: true, StrictRouting: true, ServerHeader: "Fiber", @@ -37,52 +38,185 @@ app := fiber.New(fiber.Config{ // ... ``` -**Config fields** +#### Config fields -| Property | Type | Description | Default | -| ---------------------------- | --------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| --------------------- | -| AppName | `string` | This allows to setup app name for the app | `""` | -| BodyLimit | `int` | Sets the maximum allowed size for a request body, if the size exceeds the configured limit, it sends `413 - Request Entity Too Large` response. | `4 * 1024 * 1024` | -| CaseSensitive | `bool` | When enabled, `/Foo` and `/foo` are different routes. When disabled, `/Foo`and `/foo` are treated the same. | `false` | +| Property | Type | Description | Default | +|------------------------------|-------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------| +| AppName | `string` | This allows to setup app name for the app | `""` | +| BodyLimit | `int` | Sets the maximum allowed size for a request body, if the size exceeds the configured limit, it sends `413 - Request Entity Too Large` response. | `4 * 1024 * 1024` | +| CaseSensitive | `bool` | When enabled, `/Foo` and `/foo` are different routes. When disabled, `/Foo`and `/foo` are treated the same. | `false` | | ColorScheme | [`Colors`](https://github.com/gofiber/fiber/blob/master/color.go) | You can define custom color scheme. They'll be used for startup message, route list and some middlewares. | [`DefaultColors`](https://github.com/gofiber/fiber/blob/master/color.go) | -| CompressedFileSuffix | `string` | Adds a suffix to the original file name and tries saving the resulting compressed file under the new file name. | `".fiber.gz"` | -| Concurrency | `int` | Maximum number of concurrent connections. | `256 * 1024` | -| DisableDefaultContentType | `bool` | When set to true, causes the default Content-Type header to be excluded from the Response. | `false` | -| DisableDefaultDate | `bool` | When set to true causes the default date header to be excluded from the response. | `false` | -| DisableHeaderNormalizing | `bool` | By default all header names are normalized: conteNT-tYPE -> Content-Type | `false` | -| DisableKeepalive | `bool` | Disable keep-alive connections, the server will close incoming connections after sending the first response to the client | `false` | -| DisablePreParseMultipartForm | `bool` | Will not pre parse Multipart Form data if set to true. This option is useful for servers that desire to treat multipart form data as a binary blob, or choose when to parse the data. | `false` | -| DisableStartupMessage | `bool` | When set to true, it will not print out debug information | `false` | -| ETag | `bool` | Enable or disable ETag header generation, since both weak and strong etags are generated using the same hashing method \(CRC-32\). Weak ETags are the default when enabled. | `false` | -| EnableIPValidation | `bool` | If set to true, `c.IP()` and `c.IPs()` will validate IP addresses before returning them. Also, `c.IP()` will return only the first valid IP rather than just the raw header value that may be a comma separated string.

**WARNING:** There is a small performance cost to doing this validation. Keep disabled if speed is your only concern and your application is behind a trusted proxy that already validates this header. | `false` | -| EnablePrintRoutes | `bool` | EnablePrintRoutes enables print all routes with their method, path, name and handler.. | `false` | -| EnableSplittingOnParsers | `bool` | EnableSplittingOnParsers splits the query/body/header parameters by comma when it's true.

For example, you can use it to parse multiple values from a query parameter like this: `/api?foo=bar,baz == foo[]=bar&foo[]=baz` | `false` | -| EnableTrustedProxyCheck | `bool` | When set to true, fiber will check whether proxy is trusted, using TrustedProxies list.

By default `c.Protocol()` will get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header, `c.IP()` will get value from `ProxyHeader` header, `c.Hostname()` will get value from X-Forwarded-Host header.
If `EnableTrustedProxyCheck` is true, and `RemoteIP` is in the list of `TrustedProxies` `c.Protocol()`, `c.IP()`, and `c.Hostname()` will have the same behaviour when `EnableTrustedProxyCheck` disabled, if `RemoteIP` isn't in the list, `c.Protocol()` will return https in case when tls connection is handled by the app, or http otherwise, `c.IP()` will return RemoteIP() from fasthttp context, `c.Hostname()` will return `fasthttp.Request.URI().Host()` | `false` | -| ErrorHandler | `ErrorHandler` | ErrorHandler is executed when an error is returned from fiber.Handler. Mounted fiber error handlers are retained by the top-level app and applied on prefix associated requests. | `DefaultErrorHandler` | -| GETOnly | `bool` | 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. | `false` | -| IdleTimeout | `time.Duration` | 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. | `nil` | -| Immutable | `bool` | When enabled, all values returned by context methods are immutable. By default, they are valid until you return from the handler; see issue [\#185](https://github.com/gofiber/fiber/issues/185). | `false` | -| JSONDecoder | `utils.JSONUnmarshal` | Allowing for flexibility in using another json library for decoding. | `json.Unmarshal` | -| JSONEncoder | `utils.JSONMarshal` | Allowing for flexibility in using another json library for encoding. | `json.Marshal` | -| Network | `string` | Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only)

**WARNING:** When prefork is set to true, only "tcp4" and "tcp6" can be chosen. | `NetworkTCP4` | -| PassLocalsToViews | `bool` | PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine. See our **Template Middleware** for supported engines. | `false` | -| Prefork | `bool` | Enables use of the[`SO_REUSEPORT`](https://lwn.net/Articles/542629/)socket option. This will spawn multiple Go processes listening on the same port. learn more about [socket sharding](https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/). **NOTE: if enabled, the application will need to be ran through a shell because prefork mode sets environment variables. If you're using Docker, make sure the app is ran with `CMD ./app` or `CMD ["sh", "-c", "/app"]`. For more info, see** [**this**](https://github.com/gofiber/fiber/issues/1021#issuecomment-730537971) **issue comment.** | `false` | -| ProxyHeader | `string` | This will enable `c.IP()` to return the value of the given header key. By default `c.IP()`will return the Remote IP from the TCP connection, this property can be useful if you are behind a load balancer e.g. _X-Forwarded-\*_. | `""` | -| ReadBufferSize | `int` | 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\). | `4096` | -| ReadTimeout | `time.Duration` | The amount of time allowed to read the full request, including the body. The default timeout is unlimited. | `nil` | -| RequestMethods | `[]string` | RequestMethods provides customizibility for HTTP methods. You can add/remove methods as you wish. | `DefaultMethods` | -| ServerHeader | `string` | Enables the `Server` HTTP header with the given value. | `""` | -| StreamRequestBody | `bool` | StreamRequestBody enables request body streaming, and calls the handler sooner when given body is larger than the current limit. | `false` | -| StrictRouting | `bool` | When enabled, the router treats `/foo` and `/foo/` as different. Otherwise, the router treats `/foo` and `/foo/` as the same. | `false` | -| TrustedProxies | `[]string` | Contains the list of trusted proxy IP's. Look at `EnableTrustedProxyCheck` doc.

It can take IP or IP range addresses. | `[]string*__*` | -| UnescapePath | `bool` | Converts all encoded characters in the route back before setting the path for the context, so that the routing can also work with URL encoded special characters | `false` | -| Views | `Views` | Views is the interface that wraps the Render function. See our **Template Middleware** for supported engines. | `nil` | -| ViewsLayout | `string` | Views Layout is the global layout for all template render until override on Render function. See our **Template Middleware** for supported engines. | `""` | -| WriteBufferSize | `int` | Per-connection buffer size for responses' writing. | `4096` | -| WriteTimeout | `time.Duration` | The maximum duration before timing out writes of the response. The default timeout is unlimited. | `nil` | -| XMLEncoder | `utils.XMLMarshal` | Allowing for flexibility in using another XML library for encoding. | `xml.Marshal` | - -## NewError +| CompressedFileSuffix | `string` | Adds a suffix to the original file name and tries saving the resulting compressed file under the new file name. | `".fiber.gz"` | +| Concurrency | `int` | Maximum number of concurrent connections. | `256 * 1024` | +| DisableDefaultContentType | `bool` | When set to true, causes the default Content-Type header to be excluded from the Response. | `false` | +| DisableDefaultDate | `bool` | When set to true causes the default date header to be excluded from the response. | `false` | +| DisableHeaderNormalizing | `bool` | By default all header names are normalized: conteNT-tYPE -> Content-Type | `false` | +| DisableKeepalive | `bool` | Disable keep-alive connections, the server will close incoming connections after sending the first response to the client | `false` | +| DisablePreParseMultipartForm | `bool` | Will not pre parse Multipart Form data if set to true. This option is useful for servers that desire to treat multipart form data as a binary blob, or choose when to parse the data. | `false` | +| EnableIPValidation | `bool` | If set to true, `c.IP()` and `c.IPs()` will validate IP addresses before returning them. Also, `c.IP()` will return only the first valid IP rather than just the raw header value that may be a comma separated string.

**WARNING:** There is a small performance cost to doing this validation. Keep disabled if speed is your only concern and your application is behind a trusted proxy that already validates this header. | `false` | +| EnableSplittingOnParsers | `bool` | EnableSplittingOnParsers splits the query/body/header parameters by comma when it's true.

For example, you can use it to parse multiple values from a query parameter like this: `/api?foo=bar,baz == foo[]=bar&foo[]=baz` | `false` | +| EnableTrustedProxyCheck | `bool` | When set to true, fiber will check whether proxy is trusted, using TrustedProxies list.

By default `c.Protocol()` will get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header, `c.IP()` will get value from `ProxyHeader` header, `c.Hostname()` will get value from X-Forwarded-Host header.
If `EnableTrustedProxyCheck` is true, and `RemoteIP` is in the list of `TrustedProxies` `c.Protocol()`, `c.IP()`, and `c.Hostname()` will have the same behaviour when `EnableTrustedProxyCheck` disabled, if `RemoteIP` isn't in the list, `c.Protocol()` will return https in case when tls connection is handled by the app, or http otherwise, `c.IP()` will return RemoteIP() from fasthttp context, `c.Hostname()` will return `fasthttp.Request.URI().Host()` | `false` | +| ErrorHandler | `ErrorHandler` | ErrorHandler is executed when an error is returned from fiber.Handler. Mounted fiber error handlers are retained by the top-level app and applied on prefix associated requests. | `DefaultErrorHandler` | +| GETOnly | `bool` | 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. | `false` | +| IdleTimeout | `time.Duration` | 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. | `nil` | +| Immutable | `bool` | When enabled, all values returned by context methods are immutable. By default, they are valid until you return from the handler; see issue [\#185](https://github.com/gofiber/fiber/issues/185). | `false` | +| JSONDecoder | `utils.JSONUnmarshal` | Allowing for flexibility in using another json library for decoding. | `json.Unmarshal` | +| JSONEncoder | `utils.JSONMarshal` | Allowing for flexibility in using another json library for encoding. | `json.Marshal` | +| PassLocalsToViews | `bool` | PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine. See our **Template Middleware** for supported engines. | `false` | +| ProxyHeader | `string` | This will enable `c.IP()` to return the value of the given header key. By default `c.IP()`will return the Remote IP from the TCP connection, this property can be useful if you are behind a load balancer e.g. _X-Forwarded-\*_. | `""` | +| ReadBufferSize | `int` | 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\). | `4096` | +| ReadTimeout | `time.Duration` | The amount of time allowed to read the full request, including the body. The default timeout is unlimited. | `nil` | +| ReduceMemoryUsage | `bool` | Aggressively reduces memory usage at the cost of higher CPU usage if set to true. | `false` | +| RequestMethods | `[]string` | RequestMethods provides customizibility for HTTP methods. You can add/remove methods as you wish. | `DefaultMethods` | +| ServerHeader | `string` | Enables the `Server` HTTP header with the given value. | `""` | +| StreamRequestBody | `bool` | StreamRequestBody enables request body streaming, and calls the handler sooner when given body is larger than the current limit. | `false` | +| StrictRouting | `bool` | When enabled, the router treats `/foo` and `/foo/` as different. Otherwise, the router treats `/foo` and `/foo/` as the same. | `false` | +| StructValidator | `StructValidator` | If you want to validate header/form/query... automatically when to bind, you can define struct validator. Fiber doesn't have default validator, so it'll skip validator step if you don't use any validator. | `nil` | +| TrustedProxies | `[]string` | Contains the list of trusted proxy IP's. Look at `EnableTrustedProxyCheck` doc.

It can take IP or IP range addresses. | `nil` | +| UnescapePath | `bool` | Converts all encoded characters in the route back before setting the path for the context, so that the routing can also work with URL encoded special characters | `false` | +| Views | `Views` | Views is the interface that wraps the Render function. See our **Template Middleware** for supported engines. | `nil` | +| ViewsLayout | `string` | Views Layout is the global layout for all template render until override on Render function. See our **Template Middleware** for supported engines. | `""` | +| WriteBufferSize | `int` | Per-connection buffer size for responses' writing. | `4096` | +| WriteTimeout | `time.Duration` | The maximum duration before timing out writes of the response. The default timeout is unlimited. | `nil` | +| XMLEncoder | `utils.XMLMarshal` | Allowing for flexibility in using another XML library for encoding. | `xml.Marshal` | + + +## Server listening + +### Config + +You can pass an optional ListenConfig when calling the [`Listen`](#listen) or [`Listener`](#listener) method. + +```go title="Example" +// Custom config +app.Listen(":8080", fiber.ListenConfig{ + EnablePrefork: true, + DisableStartupMessage: true, +}) +``` + +#### Config fields + +| Property | Type | Description | Default | +|-----------------------|-------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|---------| +| BeforeServeFunc | `func(app *App) error` | Allows customizing and accessing fiber app before serving the app. | `nil` | +| CertClientFile | `string` | Path of the client certificate. If you want to use mTLS, you must enter this field. | `""` | +| CertFile | `string` | Path of the certificate file. If you want to use TLS, you must enter this field. | `""` | +| CertKeyFile | `string` | Path of the certificate's private key. If you want to use TLS, you must enter this field. | `""` | +| DisableStartupMessage | `bool` | When set to true, it will not print out the Β«FiberΒ» ASCII art and listening address. | `false` | +| EnablePrefork | `bool` | When set to true, this will spawn multiple Go processes listening on the same port. | `false` | +| EnablePrintRoutes | `bool` | If set to true, will print all routes with their method, path, and handler. | `false` | +| GracefulContext | `context.Context` | Field to shutdown Fiber by given context gracefully. | `nil` | +| ListenerAddrFunc | `func(addr net.Addr)` | Allows accessing and customizing `net.Listener`. | `nil` | +| ListenerNetwork | `string` | Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only). WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen. | `tcp4` | +| OnShutdownError | `func(err error)` | Allows to customize error behavior when gracefully shutting down the server by given signal. Prints error with `log.Fatalf()` | `nil` | +| OnShutdownSuccess | `func()` | Allows to customize success behavior when gracefully shutting down the server by given signal. | `nil` | +| TLSConfigFunc | `func(tlsConfig *tls.Config)` | Allows customizing `tls.Config` as you want. | `nil` | + + +### Listen + +Listen serves HTTP requests from the given address. + +```go title="Signature" +func (app *App) Listen(addr string, config ...ListenConfig) error +``` + +```go title="Examples" +// Listen on port :8080 +app.Listen(":8080") + +// Listen on port :8080 with Prefork +app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true}) + +// Custom host +app.Listen("127.0.0.1:8080") +``` + +#### Prefork + +Prefork is a feature that allows you to spawn multiple Go processes listening on the same port. This can be useful for scaling across multiple CPU cores. + +```go title="Examples" +app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true}) +``` + +This distributes the incoming connections between the spawned processes and allows more requests to be handled simultaneously. + +#### TLS + +TLS serves HTTPs requests from the given address using certFile and keyFile paths to as TLS certificate and key file. + +```go title="Examples" +app.Listen(":443", fiber.ListenConfig{CertFile: "./cert.pem", CertKeyFile: "./cert.key"}) +``` + +#### TLS with certificate + +```go title="Examples" +app.Listen(":443", fiber.ListenConfig{CertClientFile: "./ca-chain-cert.pem"}) +``` + +#### TLS with certFile, keyFile and clientCertFile + +```go title="Examples" +app.Listen(":443", fiber.ListenConfig{CertFile: "./cert.pem", CertKeyFile: "./cert.key", CertClientFile: "./ca-chain-cert.pem"}) +``` + +### Listener + +You can pass your own [`net.Listener`](https://pkg.go.dev/net/#Listener) using the `Listener` method. This method can be used to enable **TLS/HTTPS** with a custom tls.Config. + +```go title="Signature" +func (app *App) Listener(ln net.Listener, config ...ListenConfig) error +``` + +```go title="Examples" +ln, _ := net.Listen("tcp", ":3000") + +cer, _:= tls.LoadX509KeyPair("server.crt", "server.key") + +ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cer}}) + +app.Listener(ln) +``` + +## Server + +Server returns the underlying [fasthttp server](https://godoc.org/github.com/valyala/fasthttp#Server) + +```go title="Signature" +func (app *App) Server() *fasthttp.Server +``` + +```go title="Examples" +func main() { + app := fiber.New() + + app.Server().MaxConnsPerIP = 1 + + // ... +} +``` + +## Server Shutdown + +Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waits indefinitely for all connections to return to idle before shutting down. + +ShutdownWithTimeout will forcefully close any active connections after the timeout expires. + +ShutdownWithContext shuts down the server including by force if the context's deadline is exceeded. + +```go +func (app *App) Shutdown() error +func (app *App) ShutdownWithTimeout(timeout time.Duration) error +func (app *App) ShutdownWithContext(ctx context.Context) error +``` + + +## Helper functions + +### NewError NewError creates a new HTTPError instance with an optional message. @@ -96,7 +230,7 @@ app.Get("/", func(c fiber.Ctx) error { }) ``` -## IsChild +### IsChild IsChild determines if the current process is a result of Prefork. @@ -105,16 +239,20 @@ func IsChild() bool ``` ```go title="Example" -// Prefork will spawn child processes -app := fiber.New(fiber.Config{ - Prefork: true, -}) +// Config app +app := fiber.New() -if !fiber.IsChild() { - fmt.Println("I'm the parent process") -} else { - fmt.Println("I'm a child process") -} +app.Get("/", func(c fiber.Ctx) error { + if !fiber.IsChild() { + fmt.Println("I'm the parent process") + } else { + fmt.Println("I'm a child process") + } + return c.SendString("Hello, World!") +}) // ... + +// With prefork enabled, the parent process will spawn child processes +app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true}) ``` diff --git a/docs/core/extra/_category_.json b/docs/core/extra/_category_.json index f17f137ab38..1ffd2f1b823 100644 --- a/docs/core/extra/_category_.json +++ b/docs/core/extra/_category_.json @@ -5,4 +5,4 @@ "type": "generated-index", "description": "Extra contents for Fiber." } -} \ No newline at end of file +} diff --git a/docs/core/guide/routing.md b/docs/core/guide/routing.md index 3de5bb73658..b89f4536f4a 100644 --- a/docs/core/guide/routing.md +++ b/docs/core/guide/routing.md @@ -164,7 +164,7 @@ Constraints aren't validation for parameters. If constraints aren't valid for a | datetime | :dob | 2005-11-01 | | regex(expression) | :date | 2022-08-27 (Must match regular expression) | -**Examples** +#### Examples @@ -240,7 +240,7 @@ app.Get("/:test?", func(c fiber.Ctx) error { // Cannot GET /7.0 ``` -**Custom Constraint Example** +#### Custom Constraint Custom constraints can be added to Fiber using the `app.RegisterCustomConstraint` method. Your constraints have to be compatible with the `CustomConstraint` interface. diff --git a/docs/core/intro.md b/docs/core/intro.md index 1814a34eca2..6dbc6ca7643 100644 --- a/docs/core/intro.md +++ b/docs/core/intro.md @@ -92,7 +92,7 @@ func main() { } ``` -```text +```bash go run server.go ``` diff --git a/docs/core/whats_new.md b/docs/core/whats_new.md new file mode 100644 index 00000000000..414d8c6a531 --- /dev/null +++ b/docs/core/whats_new.md @@ -0,0 +1,29 @@ +--- +id: whats_new +title: πŸ†• Whats New in v3 +sidebar_position: 2 +--- + +## πŸŽ‰ Welcome to Fiber v3 + +We are excited to announce the release of Fiber v3! πŸš€ + +Fiber v3 is a major release with a lot of new features, improvements, and breaking changes. We have worked hard to make Fiber even faster, more flexible, and easier to use. + +## πŸš€ Highlights + +### Drop for old Go versions +### App changes + +- Listen functions reduced + +### Context change +#### interface +#### customizable +### Client package +### Binding +### Generic functions +### Middleware refactoring +#### Session middleware +#### Filesystem middleware +... diff --git a/sidebars.js b/sidebars.js index 4011c81523e..27cd431f41e 100644 --- a/sidebars.js +++ b/sidebars.js @@ -14,7 +14,8 @@ /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { tutorialSidebar: [ - {type: 'doc', label: 'πŸ‘‹ Welcome', id: 'welcome'}, + {type: 'doc', id: 'welcome'}, + {type: 'doc', id: 'whats_new'}, {type: 'category', label: 'API', link: {type: 'generated-index', description: 'API documentation for Fiber.'}, items: [{type: 'autogenerated', dirName: 'api'}]}, {type: 'category', label: 'Guide', link: {type: 'generated-index', description: 'Guides for Fiber.'}, items: [{type: 'autogenerated', dirName: 'guide'}]}, {type: 'category', label: 'Extra', link: {type: 'generated-index', description: 'Extra contents for Fiber.'}, items: [{type: 'autogenerated', dirName: 'extra'}]}, From ba83c1b11472e4668e2d99c9fd35df5f3b8d28ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 16 Apr 2024 14:08:36 +0200 Subject: [PATCH 2/3] [v3-Maintenance]-Consolidate-and-Document-Core-Changes-in-v3 --- docs/core/api/ctx.md | 67 ++++++++++++++------------------------------ 1 file changed, 21 insertions(+), 46 deletions(-) diff --git a/docs/core/api/ctx.md b/docs/core/api/ctx.md index 3b86ae0f9c3..5c7cf7e8e72 100644 --- a/docs/core/api/ctx.md +++ b/docs/core/api/ctx.md @@ -100,31 +100,6 @@ app.Get("/", func(c fiber.Ctx) error { }) ``` -## AllParams - -Params is used to get all route parameters. -Using Params method to get params. - -```go title="Signature" -func (c Ctx) AllParams() map[string]string -``` - -```go title="Example" -// GET http://example.com/user/fenny -app.Get("/user/:name", func(c fiber.Ctx) error { - c.AllParams() // "{"name": "fenny"}" - - // ... -}) - -// GET http://example.com/user/fenny/123 -app.Get("/user/*", func(c fiber.Ctx) error { - c.AllParams() // "{"*1": "fenny/123"}" - - // ... -}) -``` - ## App Returns the [\*App](ctx.md) reference so you could easily access all application settings. @@ -242,27 +217,6 @@ app.Get("/", func(c fiber.Ctx) error { }) ``` -## Bind - -Add vars to default view var map binding to template engine. -Variables are read by the Render method and may be overwritten. - -```go title="Signature" -func (c Ctx) Bind(vars Map) error -``` - -```go title="Example" -app.Use(func(c fiber.Ctx) error { - c.Bind(fiber.Map{ - "Title": "Hello, World!", - }) -}) - -app.Get("/", func(c fiber.Ctx) error { - return c.Render("xxx.tmpl", fiber.Map{}) // Render will use Title variable -}) -``` - ## BodyRaw Returns the raw request **body**. @@ -2103,6 +2057,27 @@ app.Get("/", func(c fiber.Ctx) error { }) ``` +## ViewBind + +Add vars to default view var map binding to template engine. +Variables are read by the Render method and may be overwritten. + +```go title="Signature" +func (c Ctx) ViewBind(vars Map) error +``` + +```go title="Example" +app.Use(func(c fiber.Ctx) error { + c.ViewBind(fiber.Map{ + "Title": "Hello, World!", + }) +}) + +app.Get("/", func(c fiber.Ctx) error { + return c.Render("xxx.tmpl", fiber.Map{}) // Render will use Title variable +}) +``` + ## Write Write adopts the Writer interface From b847cea58dda5e5be45127a40481b38186bfd64d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 16 Apr 2024 14:12:33 +0200 Subject: [PATCH 3/3] [v3-Maintenance]-Consolidate-and-Document-Core-Changes-in-v3 --- docs/core/whats_new.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/core/whats_new.md b/docs/core/whats_new.md index 414d8c6a531..44047651ce3 100644 --- a/docs/core/whats_new.md +++ b/docs/core/whats_new.md @@ -4,6 +4,14 @@ title: πŸ†• Whats New in v3 sidebar_position: 2 --- +:::caution + +Its a draft, not finished yet. + +::: + +[//]: # (https://github.com/gofiber/fiber/releases/tag/v3.0.0-beta.2) + ## πŸŽ‰ Welcome to Fiber v3 We are excited to announce the release of Fiber v3! πŸš€ @@ -26,4 +34,6 @@ Fiber v3 is a major release with a lot of new features, improvements, and breaki ### Middleware refactoring #### Session middleware #### Filesystem middleware + +## Migration guide ...