Merge pull request #3317 from gofiber/improve_docs

docs: Update adapter middleware documentation
pull/3322/head
Juan Calderon-Perez 2025-02-20 08:26:16 -05:00 committed by GitHub
commit 252a0221a0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 95 additions and 69 deletions

View File

@ -30,7 +30,7 @@ app.Use(func(c fiber.Ctx) error {
}) })
``` ```
## How can i use live reload ? ## How can I use live reload?
[Air](https://github.com/air-verse/air) is a handy tool that automatically restarts your Go applications whenever the source code changes, making your development process faster and more efficient. [Air](https://github.com/air-verse/air) is a handy tool that automatically restarts your Go applications whenever the source code changes, making your development process faster and more efficient.
@ -99,10 +99,12 @@ If you have questions or just want to have a chat, feel free to join us via this
![](/img/support-discord.png) ![](/img/support-discord.png)
## Does fiber support sub domain routing ? ## Does Fiber support subdomain routing?
Yes we do, here are some examples: Yes we do, here are some examples:
This example works v2
<details>
<summary>Example</summary>
```go ```go
package main package main
@ -170,4 +172,18 @@ func main() {
} }
``` ```
</details>
If more information is needed, please refer to this issue [#750](https://github.com/gofiber/fiber/issues/750) If more information is needed, please refer to this issue [#750](https://github.com/gofiber/fiber/issues/750)
## How can I handle conversions between Fiber and net/http?
The `adaptor` middleware provides utilities for converting between Fiber and `net/http`. It allows seamless integration of `net/http` handlers, middleware, and requests into Fiber applications, and vice versa.
For details on how to:
* Convert `net/http` handlers to Fiber handlers
* Convert Fiber handlers to `net/http` handlers
* Convert `fiber.Ctx` to `http.Request`
See the dedicated documentation: [Adaptor Documentation](../middleware/adaptor.md).

View File

@ -4,24 +4,34 @@ id: adaptor
# Adaptor # Adaptor
Converter for net/http handlers to/from Fiber request handlers, special thanks to [@arsmn](https://github.com/arsmn)! The `adaptor` package provides utilities for converting between Fiber and `net/http`. It allows seamless integration of `net/http` handlers, middleware, and requests into Fiber applications, and vice versa.
## Signatures ## Features
| Name | Signature | Description - Convert `net/http` handlers and middleware to Fiber handlers.
| :--- | :--- | :--- - Convert Fiber handlers to `net/http` handlers.
| HTTPHandler | `HTTPHandler(h http.Handler) fiber.Handler` | http.Handler -> fiber.Handler - Convert Fiber context (`fiber.Ctx`) into an `http.Request`.
| HTTPHandlerFunc | `HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler` | http.HandlerFunc -> fiber.Handler
| HTTPMiddleware | `HTTPHandlerFunc(mw func(http.Handler) http.Handler) fiber.Handler` | func(http.Handler) http.Handler -> fiber.Handler
| FiberHandler | `FiberHandler(h fiber.Handler) http.Handler` | fiber.Handler -> http.Handler
| FiberHandlerFunc | `FiberHandlerFunc(h fiber.Handler) http.HandlerFunc` | fiber.Handler -> http.HandlerFunc
| FiberApp | `FiberApp(app *fiber.App) http.HandlerFunc` | Fiber app -> http.HandlerFunc
| ConvertRequest | `ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error)` | fiber.Ctx -> http.Request
| CopyContextToFiberContext | `CopyContextToFiberContext(context any, requestContext *fasthttp.RequestCtx)` | context.Context -> fasthttp.RequestCtx
## Examples ## API Reference
### net/http to Fiber | Name | Signature | Description |
|-----------------------------|-------------------------------------------------------------------------------|------------------------------------------------------------------|
| `HTTPHandler` | `HTTPHandler(h http.Handler) fiber.Handler` | Converts `http.Handler` to `fiber.Handler` |
| `HTTPHandlerFunc` | `HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler` | Converts `http.HandlerFunc` to `fiber.Handler` |
| `HTTPMiddleware` | `HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler` | Converts `http.Handler` middleware to `fiber.Handler` middleware |
| `FiberHandler` | `FiberHandler(h fiber.Handler) http.Handler` | Converts `fiber.Handler` to `http.Handler` |
| `FiberHandlerFunc` | `FiberHandlerFunc(h fiber.Handler) http.HandlerFunc` | Converts `fiber.Handler` to `http.HandlerFunc` |
| `FiberApp` | `FiberApp(app *fiber.App) http.HandlerFunc` | Converts an entire Fiber app to a `http.HandlerFunc` |
| `ConvertRequest` | `ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error)` | Converts `fiber.Ctx` into a `http.Request` |
| `CopyContextToFiberContext` | `CopyContextToFiberContext(context any, requestContext *fasthttp.RequestCtx)` | Copies `context.Context` to `fasthttp.RequestCtx` |
---
## Usage Examples
### 1. Using `net/http` Handlers in Fiber
This example demonstrates how to use standard `net/http` handlers inside a Fiber application:
```go ```go
package main package main
@ -29,35 +39,27 @@ package main
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/gofiber/fiber/v3/middleware/adaptor"
) )
func main() { func main() {
// New fiber app
app := fiber.New() app := fiber.New()
// http.Handler -> fiber.Handler // Convert a http.Handler to a Fiber handler
app.Get("/", adaptor.HTTPHandler(handler(greet))) app.Get("/", adaptor.HTTPHandler(http.HandlerFunc(helloHandler)))
// http.HandlerFunc -> fiber.Handler
app.Get("/func", adaptor.HTTPHandlerFunc(greet))
// Listen on port 3000
app.Listen(":3000") app.Listen(":3000")
} }
func handler(f http.HandlerFunc) http.Handler { func helloHandler(w http.ResponseWriter, r *http.Request) {
return http.HandlerFunc(f) fmt.Fprint(w, "Hello from net/http!")
}
func greet(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello World!")
} }
``` ```
### net/http middleware to Fiber ### 2. Using `net/http` Middleware with Fiber
Middleware written for `net/http` can be used in Fiber:
```go ```go
package main package main
@ -65,111 +67,119 @@ package main
import ( import (
"log" "log"
"net/http" "net/http"
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/gofiber/fiber/v3/middleware/adaptor"
) )
func main() { func main() {
// New fiber app
app := fiber.New() app := fiber.New()
// http middleware -> fiber.Handler // Apply a http middleware in Fiber
app.Use(adaptor.HTTPMiddleware(logMiddleware)) app.Use(adaptor.HTTPMiddleware(loggingMiddleware))
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello Fiber!")
})
// Listen on port 3000
app.Listen(":3000") app.Listen(":3000")
} }
func logMiddleware(next http.Handler) http.Handler { func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("log middleware") log.Println("Request received")
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
}) })
} }
``` ```
### Fiber Handler to net/http ### 3. Using Fiber Handlers in `net/http`
You can embed Fiber handlers inside `net/http`:
```go ```go
package main package main
import ( import (
"net/http" "net/http"
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/gofiber/fiber/v3/middleware/adaptor"
) )
func main() { func main() {
// fiber.Handler -> http.Handler // Convert Fiber handler to an http.Handler
http.Handle("/", adaptor.FiberHandler(greet)) http.Handle("/", adaptor.FiberHandler(helloFiber))
// fiber.Handler -> http.HandlerFunc // Convert Fiber handler to http.HandlerFunc
http.HandleFunc("/func", adaptor.FiberHandlerFunc(greet)) http.HandleFunc("/func", adaptor.FiberHandlerFunc(helloFiber))
// Listen on port 3000
http.ListenAndServe(":3000", nil) http.ListenAndServe(":3000", nil)
} }
func greet(c fiber.Ctx) error { func helloFiber(c fiber.Ctx) error {
return c.SendString("Hello World!") return c.SendString("Hello from Fiber!")
} }
``` ```
### Fiber App to net/http ### 4. Running a Fiber App in `net/http`
You can wrap a full Fiber app inside `net/http`:
```go ```go
package main package main
import ( import (
"net/http" "net/http"
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/gofiber/fiber/v3/middleware/adaptor"
) )
func main() { func main() {
app := fiber.New() app := fiber.New()
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello from Fiber!")
})
app.Get("/greet", greet) // Run Fiber inside an http server
// Listen on port 3000
http.ListenAndServe(":3000", adaptor.FiberApp(app)) http.ListenAndServe(":3000", adaptor.FiberApp(app))
} }
func greet(c fiber.Ctx) error {
return c.SendString("Hello World!")
}
``` ```
### Fiber Context to (net/http).Request ### 5. Converting Fiber Context (`fiber.Ctx`) to `http.Request`
If you need to use a `http.Request` inside a Fiber handler:
```go ```go
package main package main
import ( import (
"net/http" "net/http"
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/gofiber/fiber/v3/middleware/adaptor"
) )
func main() { func main() {
app := fiber.New() app := fiber.New()
app.Get("/request", handleRequest)
app.Get("/greet", greetWithHTTPReq) app.Listen(":3000")
// Listen on port 3000
http.ListenAndServe(":3000", adaptor.FiberApp(app))
} }
func greetWithHTTPReq(c fiber.Ctx) error { func handleRequest(c fiber.Ctx) error {
httpReq, err := adaptor.ConvertRequest(c, false) httpReq, err := adaptor.ConvertRequest(c, false)
if err != nil { if err != nil {
return err return err
} }
return c.SendString("Converted Request URL: " + httpReq.URL.String())
return c.SendString("Request URL: " + httpReq.URL.String())
} }
``` ```
---
## Summary
The `adaptor` package allows easy interoperation between Fiber and `net/http`. You can:
- Convert handlers and middleware in both directions.
- Run Fiber apps inside `net/http`.
- Convert `fiber.Ctx` to `http.Request`.
This makes it simple to integrate Fiber with existing Go projects or migrate between frameworks as needed.