Proxy

Proxy middleware for Fiber that allows you to proxy requests to multiple servers.

Signatures

  1. func Balancer(config Config) fiber.Handler
  2. func Forward(addr string) fiber.Handler
  3. func Do(c *fiber.Ctx, addr string) error

Examples

Import the middleware package that is part of the Fiber web framework

  1. import (
  2. "github.com/gofiber/fiber/v2"
  3. "github.com/gofiber/fiber/v2/middleware/proxy"
  4. )

After you initiate your Fiber app, you can use the following possibilities:

  1. // Forward to url
  2. app.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif"))
  3. // Make request within handler
  4. app.Get("/:id", func(c *fiber.Ctx) error {
  5. url := "https://i.imgur.com/"+c.Params("id")+".gif"
  6. if err := proxy.Do(c, url); err != nil {
  7. return err
  8. }
  9. // Remove Server header from response
  10. c.Response().Header.Del(fiber.HeaderServer)
  11. return nil
  12. })
  13. // Minimal round robin balancer
  14. app.Use(proxy.Balancer(proxy.Config{
  15. Servers: []string{
  16. "http://localhost:3001",
  17. "http://localhost:3002",
  18. "http://localhost:3003",
  19. },
  20. }))
  21. // Or extend your balancer for customization
  22. app.Use(proxy.Balancer(proxy.Config{
  23. Servers: []string{
  24. "http://localhost:3001",
  25. "http://localhost:3002",
  26. "http://localhost:3003",
  27. },
  28. ModifyRequest: func(c *fiber.Ctx) error {
  29. c.Request().Header.Add("X-Real-IP", c.IP())
  30. return nil
  31. },
  32. ModifyResponse: func(c *fiber.Ctx) error {
  33. c.Response().Header.Del(fiber.HeaderServer)
  34. return nil
  35. },
  36. }))

Config

  1. // Config defines the config for middleware.
  2. type Config struct {
  3. // Next defines a function to skip this middleware when returned true.
  4. //
  5. // Optional. Default: nil
  6. Next func(c *fiber.Ctx) bool
  7. // Servers defines a list of <scheme>://<host> HTTP servers,
  8. //
  9. // which are used in a round-robin manner.
  10. // i.e.: "https://foobar.com, http://www.foobar.com"
  11. //
  12. // Required
  13. Servers []string
  14. // ModifyRequest allows you to alter the request
  15. //
  16. // Optional. Default: nil
  17. ModifyRequest fiber.Handler
  18. // ModifyResponse allows you to alter the response
  19. //
  20. // Optional. Default: nil
  21. ModifyResponse fiber.Handler
  22. }

Default Config

  1. // ConfigDefault is the default config
  2. var ConfigDefault = Config{
  3. Next: nil,
  4. }