github.com/gofiber/fiber/v2@v2.47.0/docs/api/middleware/proxy.md (about)

     1  ---
     2  id: proxy
     3  title: Proxy
     4  ---
     5  
     6  Proxy middleware for [Fiber](https://github.com/gofiber/fiber) that allows you to proxy requests to multiple servers.
     7  
     8  ## Signatures
     9  
    10  ```go
    11  // Balancer create a load balancer among multiple upstrem servers.
    12  func Balancer(config Config) fiber.Handler
    13  // Forward performs the given http request and fills the given http response.
    14  func Forward(addr string, clients ...*fasthttp.Client) fiber.Handler
    15  // Do performs the given http request and fills the given http response.
    16  func Do(c *fiber.Ctx, addr string, clients ...*fasthttp.Client) error
    17  // DoRedirects performs the given http request and fills the given http response while following up to maxRedirectsCount redirects.
    18  func DoRedirects(c *fiber.Ctx, addr string, maxRedirectsCount int, clients ...*fasthttp.Client) error
    19  // DoDeadline performs the given request and waits for response until the given deadline.
    20  func DoDeadline(c *fiber.Ctx, addr string, deadline time.Time, clients ...*fasthttp.Client) error
    21  // DoTimeout performs the given request and waits for response during the given timeout duration.
    22  func DoTimeout(c *fiber.Ctx, addr string, timeout time.Duration, clients ...*fasthttp.Client) error
    23  // DomainForward the given http request based on the given domain and fills the given http response
    24  func DomainForward(hostname string, addr string, clients ...*fasthttp.Client) fiber.Handler
    25  // BalancerForward performs the given http request based round robin balancer and fills the given http response
    26  func BalancerForward(servers []string, clients ...*fasthttp.Client) fiber.Handler
    27  ```
    28  
    29  ## Examples
    30  
    31  Import the middleware package that is part of the Fiber web framework
    32  
    33  ```go
    34  import (
    35      "github.com/gofiber/fiber/v2"
    36      "github.com/gofiber/fiber/v2/middleware/proxy"
    37  )
    38  ```
    39  
    40  After you initiate your Fiber app, you can use the following possibilities:
    41  
    42  ```go
    43  // if target https site uses a self-signed certificate, you should
    44  // call WithTlsConfig before Do and Forward
    45  proxy.WithTlsConfig(&tls.Config{
    46      InsecureSkipVerify: true,
    47  })
    48  // if you need to use global self-custom client, you should use proxy.WithClient.
    49  proxy.WithClient(&fasthttp.Client{
    50      NoDefaultUserAgentHeader: true, 
    51      DisablePathNormalizing:   true,
    52  })
    53  
    54  // Forward to url
    55  app.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif"))
    56  
    57  // If you want to forward with a specific domain. You have to use proxy.DomainForward.
    58  app.Get("/payments", proxy.DomainForward("docs.gofiber.io", "http://localhost:8000"))
    59  
    60  // Forward to url with local custom client
    61  app.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif", &fasthttp.Client{
    62      NoDefaultUserAgentHeader: true, 
    63      DisablePathNormalizing:   true,
    64  }))
    65  
    66  // Make request within handler
    67  app.Get("/:id", func(c *fiber.Ctx) error {
    68      url := "https://i.imgur.com/"+c.Params("id")+".gif"
    69      if err := proxy.Do(c, url); err != nil {
    70          return err
    71      }
    72      // Remove Server header from response
    73      c.Response().Header.Del(fiber.HeaderServer)
    74      return nil
    75  })
    76  
    77  // Make proxy requests while following redirects
    78  app.Get("/proxy", func(c *fiber.Ctx) error {
    79      if err := proxy.DoRedirects(c, "http://google.com", 3); err != nil {
    80          return err
    81      }
    82      // Remove Server header from response
    83      c.Response().Header.Del(fiber.HeaderServer)
    84      return nil
    85  })
    86  
    87  // Make proxy requests and wait up to 5 seconds before timing out
    88  app.Get("/proxy", func(c *fiber.Ctx) error {
    89      if err := proxy.DoTimeout(c, "http://localhost:3000", time.Second * 5); err != nil {
    90          return err
    91      }
    92      // Remove Server header from response
    93      c.Response().Header.Del(fiber.HeaderServer)
    94      return nil
    95  })
    96  
    97  // Make proxy requests, timeout a minute from now
    98  app.Get("/proxy", func(c *fiber.Ctx) error {
    99      if err := proxy.DoDeadline(c, "http://localhost", time.Now().Add(time.Minute)); err != nil {
   100          return err
   101      }
   102      // Remove Server header from response
   103      c.Response().Header.Del(fiber.HeaderServer)
   104      return nil
   105  })
   106  
   107  // Minimal round robin balancer
   108  app.Use(proxy.Balancer(proxy.Config{
   109      Servers: []string{
   110          "http://localhost:3001",
   111          "http://localhost:3002",
   112          "http://localhost:3003",
   113      },
   114  }))
   115  
   116  // Or extend your balancer for customization
   117  app.Use(proxy.Balancer(proxy.Config{
   118      Servers: []string{
   119          "http://localhost:3001",
   120          "http://localhost:3002",
   121          "http://localhost:3003",
   122      },
   123      ModifyRequest: func(c *fiber.Ctx) error {
   124          c.Request().Header.Add("X-Real-IP", c.IP())
   125          return nil
   126      },
   127      ModifyResponse: func(c *fiber.Ctx) error {
   128          c.Response().Header.Del(fiber.HeaderServer)
   129          return nil
   130      },
   131  }))
   132  
   133  // Or this way if the balancer is using https and the destination server is only using http.
   134  app.Use(proxy.BalancerForward([]string{
   135      "http://localhost:3001",
   136      "http://localhost:3002",
   137      "http://localhost:3003",
   138  }))
   139  ```
   140  
   141  ## Config
   142  
   143  ```go
   144  // Config defines the config for middleware.
   145  type Config struct {
   146      // Next defines a function to skip this middleware when returned true.
   147      //
   148      // Optional. Default: nil
   149      Next func(c *fiber.Ctx) bool
   150  
   151      // Servers defines a list of <scheme>://<host> HTTP servers,
   152      //
   153      // which are used in a round-robin manner.
   154      // i.e.: "https://foobar.com, http://www.foobar.com"
   155      //
   156      // Required
   157      Servers []string
   158  
   159      // ModifyRequest allows you to alter the request
   160      //
   161      // Optional. Default: nil
   162      ModifyRequest fiber.Handler
   163  
   164      // ModifyResponse allows you to alter the response
   165      //
   166      // Optional. Default: nil
   167      ModifyResponse fiber.Handler
   168      
   169      // Timeout is the request timeout used when calling the proxy client
   170      //
   171      // Optional. Default: 1 second
   172      Timeout time.Duration
   173  
   174      // Per-connection buffer size for requests' reading.
   175      // This also limits the maximum header size.
   176      // Increase this buffer if your clients send multi-KB RequestURIs
   177      // and/or multi-KB headers (for example, BIG cookies).
   178      ReadBufferSize int
   179         
   180      // Per-connection buffer size for responses' writing.
   181      WriteBufferSize int
   182  
   183      // tls config for the http client.
   184      TlsConfig *tls.Config 
   185      
   186      // Client is custom client when client config is complex. 
   187      // Note that Servers, Timeout, WriteBufferSize, ReadBufferSize and TlsConfig 
   188      // will not be used if the client are set.
   189      Client *fasthttp.LBClient
   190  }
   191  ```
   192  
   193  ## Default Config
   194  
   195  ```go
   196  var ConfigDefault = Config{
   197      Next:           nil,
   198      ModifyRequest:  nil,
   199      ModifyResponse: nil,
   200      Timeout:        fasthttp.DefaultLBClientTimeout,
   201  }
   202  ```