Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement redirect capability #395

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions admin/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,6 @@ func (h *RoutesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Rate1: tg.Timer.Rate1(),
Pct99: tg.Timer.Percentile(0.99),
}
if tg.RedirectCode != 0 {
ar.Dst = fmt.Sprintf("%d|%s", tg.RedirectCode, tg.URL)
}
routes = append(routes, ar)
}
}
Expand Down
6 changes: 4 additions & 2 deletions proxy/http_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,9 @@ func TestProxyHost(t *testing.T) {
}

func TestRedirect(t *testing.T) {
routes := "route add mock /foo http://a.com/abc opts \"redirect=301\"\n"
routes += "route add mock /bar http://b.com/ opts \"redirect=302\"\n"
routes := "route add mock / http://a.com opts \"redirect=301\"\n"
routes += "route add mock /foo http://a.com/abc opts \"redirect=301\"\n"
routes += "route add mock /bar http://b.com opts \"redirect=302\"\n"
tbl, _ := route.NewTable(routes)

proxy := httptest.NewServer(&HTTPProxy{
Expand All @@ -195,6 +196,7 @@ func TestRedirect(t *testing.T) {
wantCode int
wantLoc string
}{
{req: "/", wantCode: 301, wantLoc: "http://a.com/"},
{req: "/foo", wantCode: 301, wantLoc: "http://a.com/abc"},
{req: "/bar", wantCode: 302, wantLoc: "http://b.com"},
}
Expand Down
4 changes: 2 additions & 2 deletions registry/consul/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ func TestParseTag(t *testing.T) {
ok: true,
},
{
tag: "p-www.bar.com:80/foo https://www.bar.com/ redirect=302",
tag: "p-www.bar.com:80/foo redirect=302,https://www.bar.com",
route: "www.bar.com:80/foo",
opts: "https://www.bar.com/ redirect=302",
opts: "redirect=302,https://www.bar.com",
ok: true,
},
}
Expand Down
12 changes: 10 additions & 2 deletions registry/consul/service.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package consul

import (
"fmt"
"log"
"net"
"runtime"
Expand Down Expand Up @@ -119,14 +120,21 @@ func serviceConfig(client *api.Client, name string, passing map[string]bool, tag
dst := "http://" + addr + "/"
for _, o := range strings.Fields(opts) {
switch {
case strings.Contains(o, "://"):
dst = o
case o == "proto=tcp":
dst = "tcp://" + addr
case o == "proto=https":
dst = "https://" + addr
case strings.HasPrefix(o, "weight="):
weight = o[len("weight="):]
case strings.HasPrefix(o, "redirect="):
redir := strings.Split(o[len("redirect="):], ",")
if len(redir) == 2 {
dst = redir[1]
ropts = append(ropts, fmt.Sprintf("redirect=%s", redir[0]))
} else {
log.Printf("[ERROR] Invalid syntax for redirect: %s. should be redirect=<code>,<url>", o)
continue
}
default:
ropts = append(ropts, o)
}
Expand Down
21 changes: 11 additions & 10 deletions route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,15 @@ func (r *Route) addTarget(service string, targetURL *url.URL, fixedWeight float6
t.StripPath = opts["strip"]
t.TLSSkipVerify = opts["tlsskipverify"] == "true"
t.Host = opts["host"]
t.RedirectCode, _ = strconv.Atoi(opts["redirect"])
if t.RedirectCode < 300 || t.RedirectCode > 399 {
t.RedirectCode = 0

if opts["redirect"] != "" {
t.RedirectCode, err = strconv.Atoi(opts["redirect"])
if err != nil {
log.Printf("[ERROR] redirect status code should be numeric in 3xx range. Got: %s", opts["redirect"])
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally these kind of errors should prevent the route from being added, but that would take some refactoring.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That could be added the route parser but then it would need to treat opts not as an opaque k/v string. I can have a look at this if and when I write a better parser.

} else if t.RedirectCode < 300 || t.RedirectCode > 399 {
t.RedirectCode = 0
log.Printf("[ERROR] redirect status code should in 3xx range. Got: %s", opts["redirect"])
}
}
}

Expand Down Expand Up @@ -139,12 +145,7 @@ func contains(src, dst []string) bool {
}

func (r *Route) TargetConfig(t *Target, addWeight bool) string {
s := fmt.Sprintf("route add %s %s", t.Service, r.Host+r.Path)
if t.RedirectCode != 0 {
s += fmt.Sprintf(" %d|%s", t.RedirectCode, t.URL)
} else {
s += fmt.Sprintf(" %s", t.URL)
}
s := fmt.Sprintf("route add %s %s %s", t.Service, r.Host+r.Path, t.URL)
if addWeight {
s += fmt.Sprintf(" weight %2.4f", t.Weight)
} else if t.FixedWeight > 0 {
Expand Down Expand Up @@ -225,7 +226,7 @@ func (r *Route) weighTargets() {
}

// compute the weight for the targets with dynamic weights
dynamic := float64(1-sumFixed) / float64(len(r.Targets)-nFixed)
dynamic := (1 - sumFixed) / float64(len(r.Targets)-nFixed)
if dynamic < 0 {
dynamic = 0
}
Expand Down
10 changes: 5 additions & 5 deletions route/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,12 @@ func (t Table) route(host, path string) *Route {

// normalizeHost returns the hostname from the request
// and removes the default port if present.
func normalizeHost(host string, req *http.Request) string {
func normalizeHost(host string, tls bool) string {
host = strings.ToLower(host)
if req.TLS == nil && strings.HasSuffix(host, ":80") {
if !tls && strings.HasSuffix(host, ":80") {
return host[:len(host)-len(":80")]
}
if req.TLS != nil && strings.HasSuffix(host, ":443") {
if tls && strings.HasSuffix(host, ":443") {
return host[:len(host)-len(":443")]
}
return host
Expand All @@ -287,9 +287,9 @@ func normalizeHost(host string, req *http.Request) string {
// matchingHosts returns all keys (host name patterns) from the
// routing table which match the normalized request hostname.
func (t Table) matchingHosts(req *http.Request) (hosts []string) {
host := normalizeHost(req.Host, req)
host := normalizeHost(req.Host, req.TLS != nil)
for pattern := range t {
normpat := normalizeHost(pattern, req)
normpat := normalizeHost(pattern, req.TLS != nil)
if glob.Glob(normpat, host) {
hosts = append(hosts, pattern)
}
Expand Down
3 changes: 0 additions & 3 deletions route/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,9 +416,6 @@ func TestTableParse(t *testing.T) {
targetURLs := make([]string, len(r.wTargets))
for i, tg := range r.wTargets {
targetURLs[i] = tg.URL.Scheme + "://" + tg.URL.Host + tg.URL.Path
if tg.RedirectCode != 0 {
targetURLs[i] = fmt.Sprintf("%d|%s", tg.RedirectCode, targetURLs[i])
}
}

// count how often the 'url' from 'route add svc <path> <url>'
Expand Down
1 change: 1 addition & 0 deletions route/target.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type Target struct {
URL *url.URL

// RedirectCode is the HTTP status code used for redirects.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// RedirectCode is the HTTP status code used for redirects.
// When set to a value > 0 the client is redirected to the target url.

// When set to a value > 0 the client is redirected to the target url.
RedirectCode int

// FixedWeight is the weight assigned to this target.
Expand Down