Proxy

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

Usage

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

Custom Configuration

Usage

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

Configuration

  1. // ProxyConfig defines the config for Proxy middleware.
  2. ProxyConfig struct {
  3. // Skipper defines a function to skip middleware.
  4. Skipper Skipper
  5. // Balancer defines a load balancing technique.
  6. // Required.
  7. Balancer ProxyBalancer
  8. // Rewrite defines URL path rewrite rules. The values captured in asterisk can be
  9. // retrieved by index e.g. $1, $2 and so on.
  10. Rewrite map[string]string
  11. // RegexRewrite defines rewrite rules using regexp.Rexexp with captures
  12. // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on.
  13. RegexRewrite map[*regexp.Regexp]string
  14. // Context key to store selected ProxyTarget into context.
  15. // Optional. Default value "target".
  16. ContextKey string
  17. // To customize the transport to remote.
  18. // Examples: If custom TLS certificates are required.
  19. Transport http.RoundTripper
  20. // ModifyResponse defines function to modify response from ProxyTarget.
  21. 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. e.Use(ProxyWithConfig(ProxyConfig{
  2. Balancer: rrb,
  3. Rewrite: map[string]string{
  4. "^/v1/*": "/v2/$1",
  5. },
  6. RegexRewrite: map[*regexp.Regexp]string{
  7. regexp.MustCompile("^/foo/([0-9].*)"): "/num/$1",
  8. regexp.MustCompile("^/bar/(.+?)/(.*)"): "/baz/$2/$1",
  9. },
  10. }))

Example