caddy/middleware/redirect.go

72 lines
1.2 KiB
Go
Raw Normal View History

2015-01-14 03:43:45 +08:00
package middleware
import "net/http"
2015-01-14 03:43:45 +08:00
// Redirect is middleware for redirecting certain requests
// to other locations.
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() + "'")
} 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) {
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)
}
}
}
// 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,
}