不能直接用 fasthttp.ReverseProxy 会出错,因其不兼容 net/http.Handler 接口;Fiber 基于 fasthttp,需用 fiber.Ctx.Context() 获取 *fasthttp.RequestCtx,并通过 rp.ServeHTTP() 显式调用,且必须配置 Transport 连接池与 Director 路径/Host 重写。

为什么直接用 fasthttp.ReverseProxy 会出错
Fiber 基于 fasthttp,而 fasthttp 的 ReverseProxy 并不兼容标准库的 net/http.Handler 接口。如果你照搬 net/http 的写法(比如传 http.HandlerFunc),Fiber 路由会 panic 或静默失败——因为 fasthttp 使用的是 fasthttp.RequestCtx,不是 *http.Request。
正确做法是用 fasthttp 原生的 ReverseProxy,并手动桥接 Fiber 的 fiber.Ctx 到 fasthttp.RequestCtx。
-
fiber.Ctx.Context()可以拿到底层的*fasthttp.RequestCtx - 不能直接把
fiber.Ctx当http.Handler传给旧式反代逻辑 - 所有请求头、重写、超时控制都得在
fasthttp.ReverseProxy配置里做,Fiber 中间件对代理流量无效
如何配置 fasthttp.ReverseProxy 并挂载到 Fiber 路由
核心是用 fiber.Handler 包装一个函数,内部调用 rp.ServeHTTP(ctx.Context(), ctx.Request(), ctx.Response())。
下面是最小可行示例(代理到 https://httpbin.org):
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpproxy"
)</p><p>func main() {
app := fiber.New()</p><pre class="brush:php;toolbar:false;">// 创建 ReverseProxy 实例
rp := &fasthttp.ReverseProxy{
Director: func(req *fasthttp.Request) {
// 重写目标地址
req.SetRequestURI("https://httpbin.org/get")
// 可选:透传原始 Host
req.Header.Set("X-Forwarded-Host", string(req.URI().Host()))
},
// 可选:设置代理超时
Transport: &fasthttp.Transport{
MaxConnsPerHost: 100,
MaxIdleConnDuration: 30 * time.Second,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
},
}
app.Get("/proxy/*", func(c *fiber.Ctx) error {
// 将 fiber.Ctx 转为 fasthttp 请求/响应上下文
rp.ServeHTTP(c.Context(), c.Request(), c.Response())
return nil // 不要再调用 c.Send() 或 c.JSON()
})
log.Fatal(app.Listen(":3000"))}
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
- 必须用
app.Get("/proxy/*")这类通配路由,否则路径无法透传 -
Director函数里用req.SetRequestURI(...)控制目标地址,不是拼接字符串 - 如果目标是 HTTPS,
Transport.TLSConfig.InsecureSkipVerify在开发时可设为true,生产请配置 CA - 返回前不要调用任何
c.SendXXX(),否则会 panic:response already written
如何实现路径重写和 Host 透传
默认 ReverseProxy 不改写路径,/proxy/api/users 会原样发到后端,通常这不是你想要的。你需要在 Director 中手动处理 URI。
常见需求及写法:
- 去掉前缀:
req.SetRequestURI("https://backend.com" + string(req.URI().Path())[len("/proxy"):]) - 强制设置 Host:
req.Header.Set("Host", "backend.com")(否则后端可能收不到正确 Host) - 透传原始客户端 IP:
req.Header.Set("X-Real-IP", c.IP()) - 禁止后端重定向跳转(避免 Location 返回相对路径):
req.Header.Set("Accept-Encoding", "identity")
注意:req.URI().Path() 返回的是 []byte,需用 string() 转换;路径截取要小心越界,建议加 strings.HasPrefix() 判断。
为什么 fasthttp.Transport 的连接池很重要
Fiber 默认不复用 HTTP 连接,每个代理请求都会新建 TCP 连接,高并发下容易打满文件描述符或触发 connection refused。
fasthttp.Transport 是唯一能控制连接复用、空闲超时、TLS 复用的入口:
-
MaxConnsPerHost控制单 host 最大并发连接数(建议设为 100~500) -
MaxIdleConnDuration决定空闲连接存活时间(太短频繁建连,太长占资源) - 若后端支持 HTTP/2,
Transport默认不启用,需额外配置 TLS 和 ALPN;多数场景 HTTP/1.1 + 连接池已够用 - 没有全局
DefaultTransport,每个ReverseProxy实例必须显式传Transport
漏配 Transport 是线上服务偶发超时或 502 的最常见原因。

















