From 69fe09f23b9ce07bc2e091f5fbbcf2b942c6251b Mon Sep 17 00:00:00 2001 From: wangjq4214 Date: Tue, 12 Nov 2024 16:26:40 +0800 Subject: [PATCH 01/18] feat: add a simple support for app.Listen --- listen.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/listen.go b/listen.go index 0df4e1a060..666f8de533 100644 --- a/listen.go +++ b/listen.go @@ -22,6 +22,7 @@ import ( "github.com/gofiber/fiber/v3/log" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" + "golang.org/x/crypto/acme/autocert" ) // Figlet text to show Fiber ASCII art on startup message @@ -70,6 +71,7 @@ type ListenConfig struct { // // Default: nil OnShutdownSuccess func() + // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only) // WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen. // @@ -94,6 +96,12 @@ type ListenConfig struct { // Default : "" CertClientFile string `json:"cert_client_file"` + // AutoCertManager is a acme manager for go crypto package. + // If you want to use acme, you have to provide it. + // + // Default : nil + AutoCertManager *autocert.Manager + // When set to true, it will not print out the «Fiber» ASCII art and listening address. // // Default: false @@ -176,6 +184,9 @@ func (app *App) Listen(addr string, config ...ListenConfig) error { // Attach the tlsHandler to the config app.SetTLSHandler(tlsHandler) + } else if cfg.AutoCertManager != nil { + tlsConfig.GetCertificate = cfg.AutoCertManager.GetCertificate + tlsConfig.NextProtos = append(tlsConfig.NextProtos, "http/1.1", "acme-tls/1") } if cfg.TLSConfigFunc != nil { From bd6041da71269ed35acdc91c7a508d0bee91ed15 Mon Sep 17 00:00:00 2001 From: wangjq4214 Date: Tue, 12 Nov 2024 19:30:20 +0800 Subject: [PATCH 02/18] fix: fix the nil access error --- go.mod | 1 + go.sum | 2 ++ listen.go | 6 ++++-- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 781a260a03..d223265ff3 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/tinylib/msgp v1.2.4 github.com/valyala/bytebufferpool v1.0.0 github.com/valyala/fasthttp v1.57.0 + golang.org/x/crypto v0.28.0 ) require ( diff --git a/go.sum b/go.sum index f3eb0e2468..0e17342468 100644 --- a/go.sum +++ b/go.sum @@ -35,6 +35,8 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= +golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/listen.go b/listen.go index 666f8de533..b0a060be88 100644 --- a/listen.go +++ b/listen.go @@ -185,8 +185,10 @@ func (app *App) Listen(addr string, config ...ListenConfig) error { // Attach the tlsHandler to the config app.SetTLSHandler(tlsHandler) } else if cfg.AutoCertManager != nil { - tlsConfig.GetCertificate = cfg.AutoCertManager.GetCertificate - tlsConfig.NextProtos = append(tlsConfig.NextProtos, "http/1.1", "acme-tls/1") + tlsConfig = &tls.Config{ + GetCertificate: cfg.AutoCertManager.GetCertificate, + NextProtos: []string{"http/1.1", "acme-tls/1"}, + } } if cfg.TLSConfigFunc != nil { From 1313d58061a94e09b9b2ce9530e8d4e5da27269d Mon Sep 17 00:00:00 2001 From: wangjq4214 Date: Tue, 12 Nov 2024 19:30:37 +0800 Subject: [PATCH 03/18] chore: add test case for simple tls --- listen_test.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/listen_test.go b/listen_test.go index c828a911cb..118faddf41 100644 --- a/listen_test.go +++ b/listen_test.go @@ -19,6 +19,8 @@ import ( "github.com/stretchr/testify/require" "github.com/valyala/fasthttp" "github.com/valyala/fasthttp/fasthttputil" + "golang.org/x/crypto/acme" + "golang.org/x/crypto/acme/autocert" ) // go test -run Test_Listen @@ -145,6 +147,38 @@ func Test_Listen_TLS(t *testing.T) { })) } +// go test -run Test_Listen_Acme_TLS +func Test_Listen_Acme_TLS(t *testing.T) { + // Certificate manager + m := &autocert.Manager{ + Prompt: autocert.AcceptTOS, + // Replace with your domain + HostPolicy: autocert.HostWhitelist("example.com"), + // Folder to store the certificates + Cache: autocert.DirCache("./certs"), + // Define the Client for test + Client: &acme.Client{ + DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory", + }, + } + + app := New() + + // invalid port + require.Error(t, app.Listen(":99999", ListenConfig{ + AutoCertManager: m, + })) + + go func() { + time.Sleep(1000 * time.Millisecond) + assert.NoError(t, app.Shutdown()) + }() + + require.NoError(t, app.Listen(":0", ListenConfig{ + AutoCertManager: m, + })) +} + // go test -run Test_Listen_TLS_Prefork func Test_Listen_TLS_Prefork(t *testing.T) { testPreforkMaster = true @@ -172,6 +206,42 @@ func Test_Listen_TLS_Prefork(t *testing.T) { })) } +// go test -run Test_Listen_Acme_TLS_Prefork +func Test_Listen_Acme_TLS_Prefork(t *testing.T) { + // Certificate manager + m := &autocert.Manager{ + Prompt: autocert.AcceptTOS, + // Replace with your domain + HostPolicy: autocert.HostWhitelist("example.com"), + // Folder to store the certificates + Cache: autocert.DirCache("./certs"), + // Define the Client for test + Client: &acme.Client{ + DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory", + }, + } + + app := New() + + // invalid port + require.Error(t, app.Listen(":0", ListenConfig{ + DisableStartupMessage: true, + EnablePrefork: true, + AutoCertManager: m, + })) + + go func() { + time.Sleep(1000 * time.Millisecond) + assert.NoError(t, app.Shutdown()) + }() + + require.NoError(t, app.Listen(":99999", ListenConfig{ + DisableStartupMessage: true, + EnablePrefork: true, + AutoCertManager: m, + })) +} + // go test -run Test_Listen_MutualTLS func Test_Listen_MutualTLS(t *testing.T) { app := New() From 41e00c22c3891e414f80646dabb4d45c013c99df Mon Sep 17 00:00:00 2001 From: wangjq4214 Date: Tue, 12 Nov 2024 20:29:51 +0800 Subject: [PATCH 04/18] fix: align the struct --- listen.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/listen.go b/listen.go index b0a060be88..27f8c09c00 100644 --- a/listen.go +++ b/listen.go @@ -72,6 +72,12 @@ type ListenConfig struct { // Default: nil OnShutdownSuccess func() + // AutoCertManager is a acme manager for go crypto package. + // If you want to use acme, you have to provide it. + // + // Default : nil + AutoCertManager *autocert.Manager + // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only) // WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen. // @@ -96,12 +102,6 @@ type ListenConfig struct { // Default : "" CertClientFile string `json:"cert_client_file"` - // AutoCertManager is a acme manager for go crypto package. - // If you want to use acme, you have to provide it. - // - // Default : nil - AutoCertManager *autocert.Manager - // When set to true, it will not print out the «Fiber» ASCII art and listening address. // // Default: false From 8c0542e11272e4bffabcdbcd9c95a2958e42ab8b Mon Sep 17 00:00:00 2001 From: wangjq4214 Date: Wed, 13 Nov 2024 19:59:03 +0800 Subject: [PATCH 05/18] chore: change the test case can't passed and not chack the file yet --- listen.go | 7 ++++--- listen_test.go | 18 ++++++++++++++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/listen.go b/listen.go index 27f8c09c00..dec1ba5279 100644 --- a/listen.go +++ b/listen.go @@ -72,10 +72,11 @@ type ListenConfig struct { // Default: nil OnShutdownSuccess func() - // AutoCertManager is a acme manager for go crypto package. - // If you want to use acme, you have to provide it. + // AutoCertManager manages TLS certificates automatically using the ACME protocol, + // enabling integration with Let's Encrypt or other ACME-compatible providers. + // Provide an *autocert.Manager instance to enable automatic certificate management. // - // Default : nil + // Default: nil AutoCertManager *autocert.Manager // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only) diff --git a/listen_test.go b/listen_test.go index 118faddf41..d61422cfd7 100644 --- a/listen_test.go +++ b/listen_test.go @@ -149,13 +149,18 @@ func Test_Listen_TLS(t *testing.T) { // go test -run Test_Listen_Acme_TLS func Test_Listen_Acme_TLS(t *testing.T) { + dir, _ := os.Getwd() + dir, err := os.MkdirTemp(dir, "certs") + require.NoError(t, err) + defer os.RemoveAll(dir) + // Certificate manager m := &autocert.Manager{ Prompt: autocert.AcceptTOS, // Replace with your domain HostPolicy: autocert.HostWhitelist("example.com"), // Folder to store the certificates - Cache: autocert.DirCache("./certs"), + Cache: autocert.DirCache(dir), // Define the Client for test Client: &acme.Client{ DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory", @@ -166,7 +171,8 @@ func Test_Listen_Acme_TLS(t *testing.T) { // invalid port require.Error(t, app.Listen(":99999", ListenConfig{ - AutoCertManager: m, + DisableStartupMessage: true, + AutoCertManager: m, })) go func() { @@ -175,7 +181,8 @@ func Test_Listen_Acme_TLS(t *testing.T) { }() require.NoError(t, app.Listen(":0", ListenConfig{ - AutoCertManager: m, + DisableStartupMessage: true, + AutoCertManager: m, })) } @@ -208,13 +215,16 @@ func Test_Listen_TLS_Prefork(t *testing.T) { // go test -run Test_Listen_Acme_TLS_Prefork func Test_Listen_Acme_TLS_Prefork(t *testing.T) { + dir, _ := os.MkdirTemp(".", "./certs") + defer os.RemoveAll(dir) + // Certificate manager m := &autocert.Manager{ Prompt: autocert.AcceptTOS, // Replace with your domain HostPolicy: autocert.HostWhitelist("example.com"), // Folder to store the certificates - Cache: autocert.DirCache("./certs"), + Cache: autocert.DirCache(dir), // Define the Client for test Client: &acme.Client{ DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory", From 76ccb9640165181b156d6bfa8e5df9ddb32c38e3 Mon Sep 17 00:00:00 2001 From: wangjq4214 Date: Wed, 13 Nov 2024 20:01:27 +0800 Subject: [PATCH 06/18] fix: use TLS1.2 min --- listen.go | 1 + 1 file changed, 1 insertion(+) diff --git a/listen.go b/listen.go index dec1ba5279..4bb489069d 100644 --- a/listen.go +++ b/listen.go @@ -187,6 +187,7 @@ func (app *App) Listen(addr string, config ...ListenConfig) error { app.SetTLSHandler(tlsHandler) } else if cfg.AutoCertManager != nil { tlsConfig = &tls.Config{ + MinVersion: tls.VersionTLS12, GetCertificate: cfg.AutoCertManager.GetCertificate, NextProtos: []string{"http/1.1", "acme-tls/1"}, } From bd3e06dff23b75e15ffa2d623ec2b8ce6197a725 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Fri, 29 Nov 2024 18:25:58 -0500 Subject: [PATCH 07/18] Fix lint issues --- listen_test.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/listen_test.go b/listen_test.go index d61422cfd7..589ee6a26d 100644 --- a/listen_test.go +++ b/listen_test.go @@ -149,10 +149,11 @@ func Test_Listen_TLS(t *testing.T) { // go test -run Test_Listen_Acme_TLS func Test_Listen_Acme_TLS(t *testing.T) { - dir, _ := os.Getwd() - dir, err := os.MkdirTemp(dir, "certs") + dir, err := os.Getwd() require.NoError(t, err) - defer os.RemoveAll(dir) + dir, err = os.MkdirTemp(dir, "certs") + require.NoError(t, err) + defer os.RemoveAll(dir) //nolint:errcheck // ignore error // Certificate manager m := &autocert.Manager{ @@ -215,8 +216,9 @@ func Test_Listen_TLS_Prefork(t *testing.T) { // go test -run Test_Listen_Acme_TLS_Prefork func Test_Listen_Acme_TLS_Prefork(t *testing.T) { - dir, _ := os.MkdirTemp(".", "./certs") - defer os.RemoveAll(dir) + dir, err := os.MkdirTemp(".", "./certs") + require.NoError(t, err) + defer os.RemoveAll(dir) //nolint:errcheck // ignore error // Certificate manager m := &autocert.Manager{ From a54cdf71356289b20a0e27ce743f84567439e179 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Fri, 29 Nov 2024 18:31:03 -0500 Subject: [PATCH 08/18] Fix call to os.MkdirTemp --- listen_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/listen_test.go b/listen_test.go index 589ee6a26d..3d151ed931 100644 --- a/listen_test.go +++ b/listen_test.go @@ -216,7 +216,7 @@ func Test_Listen_TLS_Prefork(t *testing.T) { // go test -run Test_Listen_Acme_TLS_Prefork func Test_Listen_Acme_TLS_Prefork(t *testing.T) { - dir, err := os.MkdirTemp(".", "./certs") + dir, err := os.MkdirTemp(".", "certs") require.NoError(t, err) defer os.RemoveAll(dir) //nolint:errcheck // ignore error From 8228e2c1834922fc2b32e6d1c355f6dc54aa381b Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Fri, 29 Nov 2024 20:02:05 -0500 Subject: [PATCH 09/18] Fix test check order --- listen_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/listen_test.go b/listen_test.go index 3d151ed931..ed102b7853 100644 --- a/listen_test.go +++ b/listen_test.go @@ -236,7 +236,7 @@ func Test_Listen_Acme_TLS_Prefork(t *testing.T) { app := New() // invalid port - require.Error(t, app.Listen(":0", ListenConfig{ + require.Error(t, app.Listen(":99999", ListenConfig{ DisableStartupMessage: true, EnablePrefork: true, AutoCertManager: m, @@ -247,7 +247,7 @@ func Test_Listen_Acme_TLS_Prefork(t *testing.T) { assert.NoError(t, app.Shutdown()) }() - require.NoError(t, app.Listen(":99999", ListenConfig{ + require.NoError(t, app.Listen(":0", ListenConfig{ DisableStartupMessage: true, EnablePrefork: true, AutoCertManager: m, From 2996935703b4e6f25bbfe174491d9de850c95955 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sat, 7 Dec 2024 23:05:10 -0500 Subject: [PATCH 10/18] Update unit-tests for ACME --- listen_test.go | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/listen_test.go b/listen_test.go index e342e817a8..5e6363963d 100644 --- a/listen_test.go +++ b/listen_test.go @@ -282,17 +282,6 @@ func Test_Listen_Acme_TLS(t *testing.T) { app := New() - // invalid port - require.Error(t, app.Listen(":99999", ListenConfig{ - DisableStartupMessage: true, - AutoCertManager: m, - })) - - go func() { - time.Sleep(1000 * time.Millisecond) - assert.NoError(t, app.Shutdown()) - }() - require.NoError(t, app.Listen(":0", ListenConfig{ DisableStartupMessage: true, AutoCertManager: m, @@ -347,18 +336,6 @@ func Test_Listen_Acme_TLS_Prefork(t *testing.T) { app := New() - // invalid port - require.Error(t, app.Listen(":99999", ListenConfig{ - DisableStartupMessage: true, - EnablePrefork: true, - AutoCertManager: m, - })) - - go func() { - time.Sleep(1000 * time.Millisecond) - assert.NoError(t, app.Shutdown()) - }() - require.NoError(t, app.Listen(":0", ListenConfig{ DisableStartupMessage: true, EnablePrefork: true, From b594117e6a8f6e3fd748fcbdfe0e222e6f876801 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sat, 7 Dec 2024 23:28:17 -0500 Subject: [PATCH 11/18] Update docs --- docs/api/fiber.md | 22 +++++++++++++++++++++- listen.go | 5 ++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/docs/api/fiber.md b/docs/api/fiber.md index 2c50339d50..3d90743dbf 100644 --- a/docs/api/fiber.md +++ b/docs/api/fiber.md @@ -114,8 +114,9 @@ app.Listen(":8080", fiber.ListenConfig{ | 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 customizing success behavior when gracefully shutting down the server by given signal. | `nil` | +| OnShutdownSuccess | `func()` | Allows customizing 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` | +| AutoCertManager | `func(tlsConfig *tls.Config)` | Manages TLS certificates automatically using the ACME protocol. Enables integration with Let's Encrypt or other ACME-compatible providers. | `nil` | ### Listen @@ -166,6 +167,25 @@ app.Listen(":443", fiber.ListenConfig{CertClientFile: "./ca-chain-cert.pem"}) app.Listen(":443", fiber.ListenConfig{CertFile: "./cert.pem", CertKeyFile: "./cert.key", CertClientFile: "./ca-chain-cert.pem"}) ``` +#### TLS AutoCert support (ACME / Let's Encrypt) + +Provides automatic access to certificates management from Let's Encrypt and any other ACME-based providers. + +```go title="Examples" +// Certificate manager +certManager := &autocert.Manager{ + Prompt: autocert.AcceptTOS, + // Replace with your domain name + HostPolicy: autocert.HostWhitelist("example.com"), + // Folder to store the certificates + Cache: autocert.DirCache("./certs"), +} + +app.Listen(":444", fiber.ListenConfig{ + AutoCertManager: certManager, +})) +``` + ### 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. diff --git a/listen.go b/listen.go index 298f5a3527..d4a097503e 100644 --- a/listen.go +++ b/listen.go @@ -72,11 +72,10 @@ type ListenConfig struct { OnShutdownSuccess func() // AutoCertManager manages TLS certificates automatically using the ACME protocol, - // enabling integration with Let's Encrypt or other ACME-compatible providers. - // Provide an *autocert.Manager instance to enable automatic certificate management. + // Enables integration with Let's Encrypt or other ACME-compatible providers. // // Default: nil - AutoCertManager *autocert.Manager + AutoCertManager *autocert.Manager `json:"auto_cert_manager"` // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only) // WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen. From 13cf2c1557a09ac41438dfdcc3d4294213356309 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sat, 7 Dec 2024 23:41:11 -0500 Subject: [PATCH 12/18] Fix identation of whats_new examples --- docs/whats_new.md | 318 +++++++++++++++++++++++----------------------- 1 file changed, 159 insertions(+), 159 deletions(-) diff --git a/docs/whats_new.md b/docs/whats_new.md index 3221f5dd5e..a4f213094b 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -175,22 +175,22 @@ The route method is now like [`Express`](https://expressjs.com/de/api.html#app.r ```go app.Route("/api").Route("/user/:id?") - .Get(func(c fiber.Ctx) error { - // Get user - return c.JSON(fiber.Map{"message": "Get user", "id": c.Params("id")}) - }) - .Post(func(c fiber.Ctx) error { - // Create user - return c.JSON(fiber.Map{"message": "User created"}) - }) - .Put(func(c fiber.Ctx) error { - // Update user - return c.JSON(fiber.Map{"message": "User updated", "id": c.Params("id")}) - }) - .Delete(func(c fiber.Ctx) error { - // Delete user - return c.JSON(fiber.Map{"message": "User deleted", "id": c.Params("id")}) - }) + .Get(func(c fiber.Ctx) error { + // Get user + return c.JSON(fiber.Map{"message": "Get user", "id": c.Params("id")}) + }) + .Post(func(c fiber.Ctx) error { + // Create user + return c.JSON(fiber.Map{"message": "User created"}) + }) + .Put(func(c fiber.Ctx) error { + // Update user + return c.JSON(fiber.Map{"message": "User updated", "id": c.Params("id")}) + }) + .Delete(func(c fiber.Ctx) error { + // Delete user + return c.JSON(fiber.Map{"message": "User deleted", "id": c.Params("id")}) + }) ``` @@ -430,11 +430,11 @@ Fiber v3 enhances the redirect functionality by introducing new methods and impr ```go app.Get("/old", func(c fiber.Ctx) error { - return c.Redirect().To("/new") + return c.Redirect().To("/new") }) app.Get("/new", func(c fiber.Ctx) error { - return c.SendString("Welcome to the new route!") + return c.SendString("Welcome to the new route!") }) ``` @@ -461,22 +461,22 @@ Fiber v3 introduces new generic functions that provide additional utility and fl package main import ( - "strconv" - "github.com/gofiber/fiber/v3" + "strconv" + "github.com/gofiber/fiber/v3" ) func main() { - app := fiber.New() + app := fiber.New() - app.Get("/convert", func(c fiber.Ctx) error { - value, err := Convert[string](c.Query("value"), strconv.Atoi, 0) - if err != nil { - return c.Status(fiber.StatusBadRequest).SendString(err.Error()) - } - return c.JSON(value) - }) + app.Get("/convert", func(c fiber.Ctx) error { + value, err := Convert[string](c.Query("value"), strconv.Atoi, 0) + if err != nil { + return c.Status(fiber.StatusBadRequest).SendString(err.Error()) + } + return c.JSON(value) + }) - app.Listen(":3000") + app.Listen(":3000") } ``` @@ -540,18 +540,18 @@ curl "http://localhost:3000/user/5" package main import ( - "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3" ) func main() { - app := fiber.New() + app := fiber.New() - app.Get("/params/:id", func(c fiber.Ctx) error { - id := Params[int](c, "id", 0) - return c.JSON(id) - }) + app.Get("/params/:id", func(c fiber.Ctx) error { + id := Params[int](c, "id", 0) + return c.JSON(id) + }) - app.Listen(":3000") + app.Listen(":3000") } ``` @@ -573,18 +573,18 @@ curl "http://localhost:3000/params/abc" package main import ( - "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3" ) func main() { - app := fiber.New() + app := fiber.New() - app.Get("/query", func(c fiber.Ctx) error { - age := Query[int](c, "age", 0) - return c.JSON(age) - }) + app.Get("/query", func(c fiber.Ctx) error { + age := Query[int](c, "age", 0) + return c.JSON(age) + }) - app.Listen(":3000") + app.Listen(":3000") } ``` @@ -607,18 +607,18 @@ curl "http://localhost:3000/query?age=abc" package main import ( - "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3" ) func main() { - app := fiber.New() + app := fiber.New() - app.Get("/header", func(c fiber.Ctx) error { - userAgent := GetReqHeader[string](c, "User-Agent", "Unknown") - return c.JSON(userAgent) - }) + app.Get("/header", func(c fiber.Ctx) error { + userAgent := GetReqHeader[string](c, "User-Agent", "Unknown") + return c.JSON(userAgent) + }) - app.Listen(":3000") + app.Listen(":3000") } ``` @@ -805,7 +805,7 @@ Since we've removed `app.Static()`, you need to move methods to static middlewar app.Static("/", "./public") app.Static("/prefix", "./public") app.Static("/prefix", "./public", Static{ - Index: "index.htm", + Index: "index.htm", }) app.Static("*", "./public/index.html") ``` @@ -815,7 +815,7 @@ app.Static("*", "./public/index.html") app.Get("/*", static.New("./public")) app.Get("/prefix*", static.New("./public")) app.Get("/prefix*", static.New("./public", static.Config{ - IndexNames: []string{"index.htm", "index.html"}, + IndexNames: []string{"index.htm", "index.html"}, })) app.Get("*", static.New("./public/index.html")) ``` @@ -831,25 +831,25 @@ We've renamed `EnableTrustedProxyCheck` to `TrustProxy` and moved `TrustedProxie ```go // Before app := fiber.New(fiber.Config{ - // EnableTrustedProxyCheck enables the trusted proxy check. - EnableTrustedProxyCheck: true, - // TrustedProxies is a list of trusted proxy IP ranges/addresses. - TrustedProxies: []string{"0.8.0.0", "127.0.0.0/8", "::1/128"}, + // EnableTrustedProxyCheck enables the trusted proxy check. + EnableTrustedProxyCheck: true, + // TrustedProxies is a list of trusted proxy IP ranges/addresses. + TrustedProxies: []string{"0.8.0.0", "127.0.0.0/8", "::1/128"}, }) ``` ```go // After app := fiber.New(fiber.Config{ - // TrustProxy enables the trusted proxy check - TrustProxy: true, - // TrustProxyConfig allows for configuring trusted proxies. - TrustProxyConfig: fiber.TrustProxyConfig{ - // Proxies is a list of trusted proxy IP ranges/addresses. - Proxies: []string{"0.8.0.0"}, - // Trust all loop-back IP addresses (127.0.0.0/8, ::1/128) - Loopback: true, - } + // TrustProxy enables the trusted proxy check + TrustProxy: true, + // TrustProxyConfig allows for configuring trusted proxies. + TrustProxyConfig: fiber.TrustProxyConfig{ + // Proxies is a list of trusted proxy IP ranges/addresses. + Proxies: []string{"0.8.0.0"}, + // Trust all loop-back IP addresses (127.0.0.0/8, ::1/128) + Loopback: true, + } }) ``` @@ -890,14 +890,14 @@ app.Route("/api", func(apiGrp Router) { ```go // After app.Route("/api").Route("/user/:id?") - .Get(func(c fiber.Ctx) error { - // Get user - return c.JSON(fiber.Map{"message": "Get user", "id": c.Params("id")}) - }) - .Post(func(c fiber.Ctx) error { - // Create user - return c.JSON(fiber.Map{"message": "User created"}) - }); + .Get(func(c fiber.Ctx) error { + // Get user + return c.JSON(fiber.Map{"message": "Get user", "id": c.Params("id")}) + }) + .Post(func(c fiber.Ctx) error { + // Create user + return c.JSON(fiber.Map{"message": "User created"}) + }); ``` ### 🗺 RebuildTree @@ -946,18 +946,18 @@ In Fiber v3, the `Ctx` parameter in handlers is now an interface, which means th package main import ( - "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2" ) func main() { - app := fiber.New() + app := fiber.New() - // Route Handler with *fiber.Ctx - app.Get("/", func(c *fiber.Ctx) error { - return c.SendString("Hello, World!") - }) + // Route Handler with *fiber.Ctx + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, World!") + }) - app.Listen(":3000") + app.Listen(":3000") } ``` @@ -967,18 +967,18 @@ func main() { package main import ( - "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3" ) func main() { - app := fiber.New() + app := fiber.New() - // Route Handler without *fiber.Ctx - app.Get("/", func(c fiber.Ctx) error { - return c.SendString("Hello, World!") - }) + // Route Handler without *fiber.Ctx + app.Get("/", func(c fiber.Ctx) error { + return c.SendString("Hello, World!") + }) - app.Listen(":3000") + app.Listen(":3000") } ``` @@ -1002,22 +1002,22 @@ The `Parser` section in Fiber v3 has undergone significant changes to improve fu ```go // Before app.Post("/user", func(c *fiber.Ctx) error { - var user User - if err := c.BodyParser(&user); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(user) + var user User + if err := c.BodyParser(&user); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(user) }) ``` ```go // After app.Post("/user", func(c fiber.Ctx) error { - var user User - if err := c.Bind().Body(&user); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(user) + var user User + if err := c.Bind().Body(&user); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(user) }) ``` @@ -1031,22 +1031,22 @@ The `Parser` section in Fiber v3 has undergone significant changes to improve fu ```go // Before app.Get("/user/:id", func(c *fiber.Ctx) error { - var params Params - if err := c.ParamsParser(¶ms); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(params) + var params Params + if err := c.ParamsParser(¶ms); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(params) }) ``` ```go // After app.Get("/user/:id", func(c fiber.Ctx) error { - var params Params - if err := c.Bind().URL(¶ms); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(params) + var params Params + if err := c.Bind().URL(¶ms); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(params) }) ``` @@ -1060,22 +1060,22 @@ The `Parser` section in Fiber v3 has undergone significant changes to improve fu ```go // Before app.Get("/search", func(c *fiber.Ctx) error { - var query Query - if err := c.QueryParser(&query); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(query) + var query Query + if err := c.QueryParser(&query); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(query) }) ``` ```go // After app.Get("/search", func(c fiber.Ctx) error { - var query Query - if err := c.Bind().Query(&query); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(query) + var query Query + if err := c.Bind().Query(&query); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(query) }) ``` @@ -1089,22 +1089,22 @@ The `Parser` section in Fiber v3 has undergone significant changes to improve fu ```go // Before app.Get("/cookie", func(c *fiber.Ctx) error { - var cookie Cookie - if err := c.CookieParser(&cookie); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(cookie) + var cookie Cookie + if err := c.CookieParser(&cookie); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(cookie) }) ``` ```go // After app.Get("/cookie", func(c fiber.Ctx) error { - var cookie Cookie - if err := c.Bind().Cookie(&cookie); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(cookie) + var cookie Cookie + if err := c.Bind().Cookie(&cookie); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(cookie) }) ``` @@ -1124,14 +1124,14 @@ Fiber v3 enhances the redirect functionality by introducing new methods and impr ```go // Before app.Get("/old", func(c *fiber.Ctx) error { - return c.RedirectToRoute("newRoute") + return c.RedirectToRoute("newRoute") }) ``` ```go // After app.Get("/old", func(c fiber.Ctx) error { - return c.Redirect().Route("newRoute") + return c.Redirect().Route("newRoute") }) ``` @@ -1145,14 +1145,14 @@ Fiber v3 enhances the redirect functionality by introducing new methods and impr ```go // Before app.Get("/back", func(c *fiber.Ctx) error { - return c.RedirectBack() + return c.RedirectBack() }) ``` ```go // After app.Get("/back", func(c fiber.Ctx) error { - return c.Redirect().Back() + return c.Redirect().Back() }) ``` @@ -1166,14 +1166,14 @@ Fiber v3 enhances the redirect functionality by introducing new methods and impr ```go // Before app.Get("/old", func(c *fiber.Ctx) error { - return c.Redirect("/new") + return c.Redirect("/new") }) ``` ```go // After app.Get("/old", func(c fiber.Ctx) error { - return c.Redirect().To("/new") + return c.Redirect().To("/new") }) ``` @@ -1248,12 +1248,12 @@ app.Use(cors.New(cors.Config{ ```go // Before app.Use(csrf.New(csrf.Config{ - Expiration: 10 * time.Minute, + Expiration: 10 * time.Minute, })) // After app.Use(csrf.New(csrf.Config{ - IdleTimeout: 10 * time.Minute, + IdleTimeout: 10 * time.Minute, })) ``` @@ -1266,28 +1266,28 @@ You need to move filesystem middleware to static middleware due to it has been r ```go // Before app.Use(filesystem.New(filesystem.Config{ - Root: http.Dir("./assets"), + Root: http.Dir("./assets"), })) app.Use(filesystem.New(filesystem.Config{ - Root: http.Dir("./assets"), - Browse: true, - Index: "index.html", - MaxAge: 3600, + Root: http.Dir("./assets"), + Browse: true, + Index: "index.html", + MaxAge: 3600, })) ``` ```go // After app.Use(static.New("", static.Config{ - FS: os.DirFS("./assets"), + FS: os.DirFS("./assets"), })) app.Use(static.New("", static.Config{ - FS: os.DirFS("./assets"), - Browse: true, - IndexNames: []string{"index.html"}, - MaxAge: 3600, + FS: os.DirFS("./assets"), + Browse: true, + IndexNames: []string{"index.html"}, + MaxAge: 3600, })) ``` @@ -1298,14 +1298,14 @@ Previously, the Healthcheck middleware was configured with a combined setup for ```go //before app.Use(healthcheck.New(healthcheck.Config{ - LivenessProbe: func(c fiber.Ctx) bool { - return true - }, - LivenessEndpoint: "/live", - ReadinessProbe: func(c fiber.Ctx) bool { - return serviceA.Ready() && serviceB.Ready() && ... - }, - ReadinessEndpoint: "/ready", + LivenessProbe: func(c fiber.Ctx) bool { + return true + }, + LivenessEndpoint: "/live", + ReadinessProbe: func(c fiber.Ctx) bool { + return serviceA.Ready() && serviceB.Ready() && ... + }, + ReadinessEndpoint: "/ready", })) ``` @@ -1316,9 +1316,9 @@ With the new version, each health check endpoint is configured separately, allow // Default liveness endpoint configuration app.Get(healthcheck.DefaultLivenessEndpoint, healthcheck.NewHealthChecker(healthcheck.Config{ - Probe: func(c fiber.Ctx) bool { - return true - }, + Probe: func(c fiber.Ctx) bool { + return true + }, })) // Default readiness endpoint configuration @@ -1327,9 +1327,9 @@ app.Get(healthcheck.DefaultReadinessEndpoint, healthcheck.NewHealthChecker()) // New default startup endpoint configuration // Default endpoint is /startupz app.Get(healthcheck.DefaultStartupEndpoint, healthcheck.NewHealthChecker(healthcheck.Config{ - Probe: func(c fiber.Ctx) bool { - return serviceA.Ready() && serviceB.Ready() && ... - }, + Probe: func(c fiber.Ctx) bool { + return serviceA.Ready() && serviceB.Ready() && ... + }, })) // Custom liveness endpoint configuration From 90bd4cc5f34861f68d5e1e0dc0dc91796eb1f38b Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sun, 8 Dec 2024 00:19:15 -0500 Subject: [PATCH 13/18] More updates to docs --- docs/whats_new.md | 99 +++++++++++++++++++++++------------------------ 1 file changed, 48 insertions(+), 51 deletions(-) diff --git a/docs/whats_new.md b/docs/whats_new.md index a4f213094b..e94479498b 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -209,14 +209,14 @@ Registering a subapp is now also possible via the [`Use`](./api/app#use) method ```go // register mulitple prefixes app.Use(["/v1", "/v2"], func(c fiber.Ctx) error { - // Middleware for /v1 and /v2 - return c.Next() + // Middleware for /v1 and /v2 + return c.Next() }) // define subapp api := fiber.New() api.Get("/user", func(c fiber.Ctx) error { - return c.SendString("User") + return c.SendString("User") }) // register subapp app.Use("/api", api) @@ -242,14 +242,14 @@ The `app.Test()` method now allows users to customize their test configurations: // Create a test app with a handler to test app := fiber.New() app.Get("/", func(c fiber.Ctx) { - return c.SendString("hello world") + return c.SendString("hello world") }) // Define the HTTP request and custom TestConfig to test the handler req := httptest.NewRequest(MethodGet, "/", nil) testConfig := fiber.TestConfig{ - Timeout: 0, - FailOnTimeout: false, + Timeout: 0, + FailOnTimeout: false, } // Test the handler using the request and testConfig @@ -277,8 +277,8 @@ If a custom `TestConfig` isn't provided, then the following will be used: ```go testConfig := fiber.TestConfig{ - Timeout: time.Second, - FailOnTimeout: true, + Timeout: time.Second, + FailOnTimeout: true, } ``` @@ -288,8 +288,8 @@ An empty `TestConfig` is the equivalent of: ```go testConfig := fiber.TestConfig{ - Timeout: 0, - FailOnTimeout: false, + Timeout: 0, + FailOnTimeout: false, } ``` @@ -340,7 +340,7 @@ testConfig := fiber.TestConfig{ ### SendStreamWriter -In v3, we added support for buffered streaming by providing the new method `SendStreamWriter()`. +In v3, we introduced support for buffered streaming with the addition of the `SendStreamWriter` method: ```go func (c Ctx) SendStreamWriter(streamWriter func(w *bufio.Writer)) @@ -354,22 +354,22 @@ With this new method, you can implement: ```go app.Get("/sse", func(c fiber.Ctx) { - c.Set("Content-Type", "text/event-stream") - c.Set("Cache-Control", "no-cache") - c.Set("Connection", "keep-alive") - c.Set("Transfer-Encoding", "chunked") - - return c.SendStreamWriter(func(w *bufio.Writer) { - for { - fmt.Fprintf(w, "event: my-event\n") - fmt.Fprintf(w, "data: Hello SSE\n\n") - - if err := w.Flush(); err != nil { - log.Print("Client disconnected!") - return - } - } - }) + c.Set("Content-Type", "text/event-stream") + c.Set("Cache-Control", "no-cache") + c.Set("Connection", "keep-alive") + c.Set("Transfer-Encoding", "chunked") + + return c.SendStreamWriter(func(w *bufio.Writer) { + for { + fmt.Fprintf(w, "event: my-event\n") + fmt.Fprintf(w, "data: Hello SSE\n\n") + + if err := w.Flush(); err != nil { + log.Print("Client disconnected!") + return + } + } + }) }) ``` @@ -397,17 +397,17 @@ Fiber v3 introduces a new binding mechanism that simplifies the process of bindi ```go type User struct { - ID int `params:"id"` - Name string `json:"name"` - Email string `json:"email"` + ID int `params:"id"` + Name string `json:"name"` + Email string `json:"email"` } app.Post("/user/:id", func(c fiber.Ctx) error { - var user User - if err := c.Bind().Body(&user); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) - } - return c.JSON(user) + var user User + if err := c.Bind().Body(&user); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()}) + } + return c.JSON(user) }) ``` @@ -553,7 +553,6 @@ func main() { app.Listen(":3000") } - ``` ```sh @@ -590,7 +589,6 @@ func main() { ``` ```sh - curl "http://localhost:3000/query?age=25" # Output: 25 @@ -902,9 +900,9 @@ app.Route("/api").Route("/user/:id?") ### 🗺 RebuildTree -We have added a new method that allows the route tree stack to be rebuilt in runtime, with it, you can add a route while your application is running and rebuild the route tree stack to make it registered and available for calls. +We introduced a new method that enables rebuilding the route tree stack at runtime. This allows you to add routes dynamically while your application is running and update the route tree to make the new routes available for use. -You can find more reference on it in the [app](./api/app.md#rebuildtree): +For more details, refer to the [app documentation](./api/app.md#rebuildtree): #### Example Usage @@ -920,10 +918,9 @@ app.Get("/define", func(c Ctx) error { // Define a new route dynamically }) ``` -In this example, a new route is defined and then `RebuildTree()` is called to make sure the new route is registered and available. +In this example, a new route is defined, and `RebuildTree()` is called to ensure the new route is registered and available. -**Note:** Use this method with caution. It is **not** thread-safe and calling it can be very performance-intensive, so it should be used sparingly and only in -development mode. Avoid using it concurrently. +Note: Use this method with caution. It is **not** thread-safe and can be very performance-intensive. Therefore, it should be used sparingly and primarily in development mode. It should not be invoke concurrently. ### 🧠 Context @@ -975,7 +972,7 @@ func main() { // Route Handler without *fiber.Ctx app.Get("/", func(c fiber.Ctx) error { - return c.SendString("Hello, World!") + return c.SendString("Hello, World!") }) app.Listen(":3000") @@ -1226,18 +1223,18 @@ The CORS middleware has been updated to use slices instead of strings for the `A ```go // Before app.Use(cors.New(cors.Config{ - AllowOrigins: "https://example.com,https://example2.com", - AllowMethods: strings.Join([]string{fiber.MethodGet, fiber.MethodPost}, ","), - AllowHeaders: "Content-Type", - ExposeHeaders: "Content-Length", + AllowOrigins: "https://example.com,https://example2.com", + AllowMethods: strings.Join([]string{fiber.MethodGet, fiber.MethodPost}, ","), + AllowHeaders: "Content-Type", + ExposeHeaders: "Content-Length", })) // After app.Use(cors.New(cors.Config{ - AllowOrigins: []string{"https://example.com", "https://example2.com"}, - AllowMethods: []string{fiber.MethodGet, fiber.MethodPost}, - AllowHeaders: []string{"Content-Type"}, - ExposeHeaders: []string{"Content-Length"}, + AllowOrigins: []string{"https://example.com", "https://example2.com"}, + AllowMethods: []string{fiber.MethodGet, fiber.MethodPost}, + AllowHeaders: []string{"Content-Type"}, + ExposeHeaders: []string{"Content-Length"}, })) ``` From c3b07e9fdc153c75190faceec5c5b23324f2c4a6 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez Date: Sun, 8 Dec 2024 19:06:51 -0500 Subject: [PATCH 14/18] Remove ACME tests. Add check for tlsConfig --- listen.go | 2 +- listen_test.go | 59 -------------------------------------------------- 2 files changed, 1 insertion(+), 60 deletions(-) diff --git a/listen.go b/listen.go index d4a097503e..e0c5536968 100644 --- a/listen.go +++ b/listen.go @@ -199,7 +199,7 @@ func (app *App) Listen(addr string, config ...ListenConfig) error { } } - if cfg.TLSConfigFunc != nil { + if tlsConfig != nil && cfg.TLSConfigFunc != nil { cfg.TLSConfigFunc(tlsConfig) } diff --git a/listen_test.go b/listen_test.go index 5e6363963d..123cf2b3b8 100644 --- a/listen_test.go +++ b/listen_test.go @@ -19,8 +19,6 @@ import ( "github.com/stretchr/testify/require" "github.com/valyala/fasthttp" "github.com/valyala/fasthttp/fasthttputil" - "golang.org/x/crypto/acme" - "golang.org/x/crypto/acme/autocert" ) // go test -run Test_Listen @@ -259,35 +257,6 @@ func Test_Listen_TLS(t *testing.T) { })) } -// go test -run Test_Listen_Acme_TLS -func Test_Listen_Acme_TLS(t *testing.T) { - dir, err := os.Getwd() - require.NoError(t, err) - dir, err = os.MkdirTemp(dir, "certs") - require.NoError(t, err) - defer os.RemoveAll(dir) //nolint:errcheck // ignore error - - // Certificate manager - m := &autocert.Manager{ - Prompt: autocert.AcceptTOS, - // Replace with your domain - HostPolicy: autocert.HostWhitelist("example.com"), - // Folder to store the certificates - Cache: autocert.DirCache(dir), - // Define the Client for test - Client: &acme.Client{ - DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory", - }, - } - - app := New() - - require.NoError(t, app.Listen(":0", ListenConfig{ - DisableStartupMessage: true, - AutoCertManager: m, - })) -} - // go test -run Test_Listen_TLS_Prefork func Test_Listen_TLS_Prefork(t *testing.T) { testPreforkMaster = true @@ -315,34 +284,6 @@ func Test_Listen_TLS_Prefork(t *testing.T) { })) } -// go test -run Test_Listen_Acme_TLS_Prefork -func Test_Listen_Acme_TLS_Prefork(t *testing.T) { - dir, err := os.MkdirTemp(".", "certs") - require.NoError(t, err) - defer os.RemoveAll(dir) //nolint:errcheck // ignore error - - // Certificate manager - m := &autocert.Manager{ - Prompt: autocert.AcceptTOS, - // Replace with your domain - HostPolicy: autocert.HostWhitelist("example.com"), - // Folder to store the certificates - Cache: autocert.DirCache(dir), - // Define the Client for test - Client: &acme.Client{ - DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory", - }, - } - - app := New() - - require.NoError(t, app.Listen(":0", ListenConfig{ - DisableStartupMessage: true, - EnablePrefork: true, - AutoCertManager: m, - })) -} - // go test -run Test_Listen_MutualTLS func Test_Listen_MutualTLS(t *testing.T) { app := New() From c80b1a2fb35a2894d22414e6bdf5902bff4d4eb4 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Mon, 9 Dec 2024 10:03:21 -0500 Subject: [PATCH 15/18] Add ACME section to whats_new docs --- docs/whats_new.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/whats_new.md b/docs/whats_new.md index e94479498b..4081a7047d 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -130,6 +130,25 @@ In this example, a custom context `CustomCtx` is created with an additional meth +#### TLS AutoCert support (ACME / Let's Encrypt) + +We have added native support for automatic certificates management from Let's Encrypt and any other ACME-based providers. + +```go +// Certificate manager +certManager := &autocert.Manager{ + Prompt: autocert.AcceptTOS, + // Replace with your domain name + HostPolicy: autocert.HostWhitelist("example.com"), + // Folder to store the certificates + Cache: autocert.DirCache("./certs"), +} + +app.Listen(":444", fiber.ListenConfig{ + AutoCertManager: certManager, +})) +``` + ## 🗺 Router We have slightly adapted our router interface From e684e1a3ca8c24b7deb8ccf87c58f8f747560035 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Mon, 9 Dec 2024 10:22:55 -0500 Subject: [PATCH 16/18] Update docs/whats_new.md Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- docs/whats_new.md | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/docs/whats_new.md b/docs/whats_new.md index 4081a7047d..b902a7a1fa 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -134,20 +134,6 @@ In this example, a custom context `CustomCtx` is created with an additional meth We have added native support for automatic certificates management from Let's Encrypt and any other ACME-based providers. -```go -// Certificate manager -certManager := &autocert.Manager{ - Prompt: autocert.AcceptTOS, - // Replace with your domain name - HostPolicy: autocert.HostWhitelist("example.com"), - // Folder to store the certificates - Cache: autocert.DirCache("./certs"), -} - -app.Listen(":444", fiber.ListenConfig{ - AutoCertManager: certManager, -})) -``` ## 🗺 Router From 12e65ec0d86bd543c0e557ac05f1b2c84a97cf30 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Mon, 9 Dec 2024 10:24:35 -0500 Subject: [PATCH 17/18] Update fiber.md --- docs/api/fiber.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/fiber.md b/docs/api/fiber.md index 3d90743dbf..a34a5d944c 100644 --- a/docs/api/fiber.md +++ b/docs/api/fiber.md @@ -183,7 +183,7 @@ certManager := &autocert.Manager{ app.Listen(":444", fiber.ListenConfig{ AutoCertManager: certManager, -})) +}) ``` ### Listener From dc11469831fbdd7f11cc93613554c4138a5a82f7 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Mon, 9 Dec 2024 10:26:49 -0500 Subject: [PATCH 18/18] Update whats_new.md --- docs/whats_new.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/whats_new.md b/docs/whats_new.md index b902a7a1fa..bfc6f25c29 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -134,6 +134,20 @@ In this example, a custom context `CustomCtx` is created with an additional meth We have added native support for automatic certificates management from Let's Encrypt and any other ACME-based providers. +```go +// Certificate manager +certManager := &autocert.Manager{ + Prompt: autocert.AcceptTOS, + // Replace with your domain name + HostPolicy: autocert.HostWhitelist("example.com"), + // Folder to store the certificates + Cache: autocert.DirCache("./certs"), +} + +app.Listen(":444", fiber.ListenConfig{ + AutoCertManager: certManager, +}) +``` ## 🗺 Router