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

Table of Contents

Signatures

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

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

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
​
8
// Servers defines a list of <scheme>://<host> HTTP servers,
9
//
10
// which are used in a round-robin manner.
11
// i.e.: "https://foobar.com, http://www.foobar.com"
12
//
13
// Required
14
Servers []string
15
​
16
// ModifyRequest allows you to alter the request
17
//
18
// Optional. Default: nil
19
ModifyRequest fiber.Handler
20
​
21
// ModifyResponse allows you to alter the response
22
//
23
// Optional. Default: nil
24
ModifyResponse fiber.Handler
25
}
Copied!

Default Config

1
// ConfigDefault is the default config
2
var ConfigDefault = Config{
3
Next: nil,
4
}
Copied!
Last modified 7mo ago