From a93db40138ed3c8b655d37d6b848277b74c81b14 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Sun, 12 Apr 2015 18:13:58 -0600 Subject: [PATCH] Improvements to the redirect middleware --- middleware/redirect/redirect.go | 35 +++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/middleware/redirect/redirect.go b/middleware/redirect/redirect.go index 09073cd62..5e7dec851 100644 --- a/middleware/redirect/redirect.go +++ b/middleware/redirect/redirect.go @@ -30,12 +30,12 @@ type Redirect struct { // ServeHTTP implements the middleware.Handler interface. func (rd Redirect) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { for _, rule := range rd.Rules { + if rule.From == "/" { + // Catchall redirect preserves path (TODO: Standardize/formalize this behavior) + http.Redirect(w, r, strings.TrimSuffix(rule.To, "/")+r.URL.Path, rule.Code) + return 0, nil + } if r.URL.Path == rule.From { - if rule.From == "/" { - // Catchall redirect preserves path (TODO: This behavior should be more standardized...) - http.Redirect(w, r, strings.TrimSuffix(rule.To, "/")+r.URL.Path, rule.Code) - return 0, nil - } http.Redirect(w, r, rule.To, rule.Code) return 0, nil } @@ -50,21 +50,31 @@ func parse(c middleware.Controller) ([]Rule, error) { var rule Rule args := c.RemainingArgs() - if len(args) == 1 { - // Only 'To' specified + switch len(args) { + case 1: + // To specified rule.From = "/" - rule.To = c.Val() - rule.Code = 307 // TODO: Consider 301 instead? - } else if len(args) == 3 { + rule.To = args[0] + rule.Code = http.StatusTemporaryRedirect + case 2: + // To and Code specified + rule.From = "/" + rule.To = args[0] + if code, ok := httpRedirs[args[1]]; !ok { + return redirects, c.Err("Invalid redirect code '" + args[1] + "'") + } else { + rule.Code = code + } + case 3: // From, To, and Code specified rule.From = args[0] rule.To = args[1] if code, ok := httpRedirs[args[2]]; !ok { - return redirects, c.Err("Invalid redirect code '" + c.Val() + "'") + return redirects, c.Err("Invalid redirect code '" + args[2] + "'") } else { rule.Code = code } - } else { + default: return redirects, c.ArgErr() } @@ -92,7 +102,6 @@ var httpRedirs = map[string]int{ "303": 303, "304": 304, "305": 305, - "306": 306, "307": 307, "308": 308, }