proxy

Proxy

原文:https://echo.labstack.com/docs/middleware/proxy

Proxy provides an HTTP/WebSocket reverse proxy middleware. It forwards a request to upstream server using a configured load balancing technique.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
url1, err := url.Parse("http://localhost:8081")
if err != nil {
  e.Logger.Fatal(err)
}
url2, err := url.Parse("http://localhost:8082")
if err != nil {
  e.Logger.Fatal(err)
}
e.Use(middleware.Proxy(middleware.NewRoundRobinBalancer([]*middleware.ProxyTarget{
  {
    URL: url1,
  },
  {
    URL: url2,
  },
})))

Custom Configuration

Usage

1
2
e := echo.New()
e.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{}))

Configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// ProxyConfig defines the config for Proxy middleware.
  ProxyConfig struct {
    // Skipper defines a function to skip middleware.
    Skipper Skipper

    // Balancer defines a load balancing technique.
    // Required.
    Balancer ProxyBalancer

    // Rewrite defines URL path rewrite rules. The values captured in asterisk can be
    // retrieved by index e.g. $1, $2 and so on.
    Rewrite map[string]string

    // RegexRewrite defines rewrite rules using regexp.Rexexp with captures
    // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on.
    RegexRewrite map[*regexp.Regexp]string

    // Context key to store selected ProxyTarget into context.
    // Optional. Default value "target".
    ContextKey string

    // To customize the transport to remote.
    // Examples: If custom TLS certificates are required.
    Transport http.RoundTripper

    // ModifyResponse defines function to modify response from ProxyTarget.
    ModifyResponse func(*http.Response) error

Default Configuration

NameValue
SkipperDefaultSkipper
ContextKeytarget

Regex-based Rules

For advanced rewriting of proxy requests rules may also be defined using regular expression. Normal capture groups can be defined using () and referenced by index ($1, $2, …) for the rewritten path.

RegexRules and normal Rules can be combined.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  e.Use(ProxyWithConfig(ProxyConfig{
    Balancer: rrb,
    Rewrite: map[string]string{
      "^/v1/*":     "/v2/$1",
    },
    RegexRewrite: map[*regexp.Regexp]string{
      regexp.MustCompile("^/foo/([0-9].*)"):  "/num/$1",
      regexp.MustCompile("^/bar/(.+?)/(.*)"): "/baz/$2/$1",
    },
  }))

Example

最后修改 October 10, 2024: 更新 (a4b8f85)