Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V3 maintenance] consolidate and document core changes in v3 #397

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 86 additions & 143 deletions docs/core/api/app.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**.

Expand Down Expand Up @@ -109,11 +111,11 @@ app.Static("/", "./public", fiber.Static{
})
```

## Route Handlers
### Route Handlers

<RoutingHandler />

## Mount
### Mount

You can Mount Fiber instance by creating a `*Mount`

Expand All @@ -135,7 +137,7 @@ func main() {
}
```

## MountPath
### MountPath

The `MountPath` property contains one or more path patterns on which a sub-app was mounted.

Expand Down Expand Up @@ -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.

Expand All @@ -191,7 +193,7 @@ func main() {
}
```

## Route
### Route

You can define routes with a common prefix inside the common function.

Expand All @@ -212,47 +214,15 @@ 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.

```go title="Signature"
func (app *App) HandlersCount() uint32
```

## Stack
### Stack

This method returns the original router stack

Expand Down Expand Up @@ -306,7 +276,7 @@ func main() {
]
```

## Name
### Name

This method assigns the name of latest created route.

Expand Down Expand Up @@ -408,7 +378,7 @@ func main() {
]
```

## GetRoute
### GetRoute

This method gets the route by name.

Expand All @@ -429,7 +399,6 @@ func main() {


app.Listen(":3000")

}
```

Expand All @@ -442,7 +411,7 @@ func main() {
}
```

## GetRoutes
### GetRoutes

This method gets all routes.

Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading