2015-01-14 03:43:45 +08:00
|
|
|
package middleware
|
|
|
|
|
2015-01-19 14:11:21 +08:00
|
|
|
import "net/http"
|
2015-01-14 03:43:45 +08:00
|
|
|
|
|
|
|
// Redirect is middleware for redirecting certain requests
|
|
|
|
// to other locations.
|
2015-01-19 14:11:21 +08: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-22 03:09:49 +08:00
|
|
|
return p.Err("Invalid redirect code '" + p.Val() + "'")
|
2015-01-19 14:11:21 +08:00
|
|
|
} else {
|
|
|
|
rule.Code = code
|
|
|
|
}
|
|
|
|
|
|
|
|
redirects = append(redirects, rule)
|
|
|
|
}
|
|
|
|
|
2015-01-14 03:43:45 +08:00
|
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2015-01-19 14:11:21 +08:00
|
|
|
for _, rule := range redirects {
|
2015-01-14 03:43:45 +08:00
|
|
|
if r.URL.Path == rule.From {
|
|
|
|
http.Redirect(w, r, rule.To, rule.Code)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
next(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-01-19 14:11:21 +08: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,
|
|
|
|
}
|