2015-01-13 14:43:45 -05:00
|
|
|
package middleware
|
|
|
|
|
2015-01-19 01:11:21 -05:00
|
|
|
import "net/http"
|
2015-01-13 14:43:45 -05:00
|
|
|
|
|
|
|
// Redirect is middleware for redirecting certain requests
|
|
|
|
// to other locations.
|
2015-01-19 01:11:21 -05:00
|
|
|
func Redirect(p parser) Middleware {
|
|
|
|
|
|
|
|
// Redirect describes an HTTP redirect rule.
|
|
|
|
type redirect struct {
|
|
|
|
From string
|
|
|
|
To string
|
|
|
|
Code int
|
|
|
|
}
|
|
|
|
|
|
|
|
var redirects []redirect
|
|
|
|
|
|
|
|
for p.Next() {
|
|
|
|
var rule redirect
|
|
|
|
|
|
|
|
// From
|
|
|
|
if !p.NextArg() {
|
|
|
|
return p.ArgErr()
|
|
|
|
}
|
|
|
|
rule.From = p.Val()
|
|
|
|
|
|
|
|
// To
|
|
|
|
if !p.NextArg() {
|
|
|
|
return p.ArgErr()
|
|
|
|
}
|
|
|
|
rule.To = p.Val()
|
|
|
|
|
|
|
|
// Status Code
|
|
|
|
if !p.NextArg() {
|
|
|
|
return p.ArgErr()
|
|
|
|
}
|
|
|
|
|
|
|
|
if code, ok := httpRedirs[p.Val()]; !ok {
|
2015-01-21 14:09:49 -05:00
|
|
|
return p.Err("Invalid redirect code '" + p.Val() + "'")
|
2015-01-19 01:11:21 -05:00
|
|
|
} else {
|
|
|
|
rule.Code = code
|
|
|
|
}
|
|
|
|
|
|
|
|
redirects = append(redirects, rule)
|
|
|
|
}
|
|
|
|
|
2015-01-13 14:43:45 -05:00
|
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2015-01-19 01:11:21 -05:00
|
|
|
for _, rule := range redirects {
|
2015-01-13 14:43:45 -05:00
|
|
|
if r.URL.Path == rule.From {
|
|
|
|
http.Redirect(w, r, rule.To, rule.Code)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
next(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-01-19 01:11:21 -05:00
|
|
|
|
|
|
|
// httpRedirs is a list of supported HTTP redirect codes.
|
|
|
|
var httpRedirs = map[string]int{
|
|
|
|
"300": 300,
|
|
|
|
"301": 301,
|
|
|
|
"302": 302,
|
|
|
|
"303": 303,
|
|
|
|
"304": 304,
|
|
|
|
"305": 305,
|
|
|
|
"306": 306,
|
|
|
|
"307": 307,
|
|
|
|
"308": 308,
|
|
|
|
}
|