Proxy middleware for Fiber that allows you to proxy requests to multiple servers.
func Balancer(config Config) fiber.Handlerfunc Forward(addr string) fiber.Handlerfunc Do(c *fiber.Ctx, addr string) error
Import the middleware package that is part of the Fiber web framework
import ("github.com/gofiber/fiber/v2""github.com/gofiber/fiber/v2/middleware/proxy")
After you initiate your Fiber app, you can use the following possibilities:
// Forward to urlapp.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif"))// Make request within handlerapp.Get("/:id", func(c *fiber.Ctx) error {url := "https://i.imgur.com/"+c.Params("id")+".gif"if err := proxy.Do(c, url); err != nil {return err}// Remove Server header from responsec.Response().Header.Del(fiber.HeaderServer)return nil})// Minimal round robin balancerapp.Use(proxy.Balancer(proxy.Config{Servers: []string{"http://localhost:3001","http://localhost:3002","http://localhost:3003",},}))// Or extend your balancer for customizationapp.Use(proxy.Balancer(proxy.Config{Servers: []string{"http://localhost:3001","http://localhost:3002","http://localhost:3003",},ModifyRequest: func(c *fiber.Ctx) error {c.Request().Header.Add("X-Real-IP", c.IP())return nil},ModifyResponse: func(c *fiber.Ctx) error {c.Response().Header.Del(fiber.HeaderServer)return nil},}))
// Config defines the config for middleware.type Config struct {// Next defines a function to skip this middleware when returned true.//// Optional. Default: nilNext func(c *fiber.Ctx) bool// Servers defines a list of <scheme>://<host> HTTP servers,//// which are used in a round-robin manner.// i.e.: "https://foobar.com, http://www.foobar.com"//// RequiredServers []string// ModifyRequest allows you to alter the request//// Optional. Default: nilModifyRequest fiber.Handler// ModifyResponse allows you to alter the response//// Optional. Default: nilModifyResponse fiber.Handler}
// ConfigDefault is the default configvar ConfigDefault = Config{Next: nil,}