2015-05-04 12:04:17 -05:00
|
|
|
package setup
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
|
|
"github.com/mholt/caddy/middleware/rewrite"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Rewrite configures a new Rewrite middleware instance.
|
|
|
|
func Rewrite(c *Controller) (middleware.Middleware, error) {
|
|
|
|
rewrites, err := rewriteParse(c)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(next middleware.Handler) middleware.Handler {
|
|
|
|
return rewrite.Rewrite{Next: next, Rules: rewrites}
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func rewriteParse(c *Controller) ([]rewrite.Rule, error) {
|
2015-05-15 12:47:26 -05:00
|
|
|
var simpleRules []rewrite.Rule
|
|
|
|
var regexpRules []rewrite.Rule
|
2015-05-04 12:04:17 -05:00
|
|
|
|
|
|
|
for c.Next() {
|
|
|
|
var rule rewrite.Rule
|
2015-05-14 20:43:29 -05:00
|
|
|
var err error
|
2015-05-15 12:47:26 -05:00
|
|
|
var base = "/"
|
|
|
|
var pattern, to string
|
|
|
|
var ext []string
|
2015-05-04 12:04:17 -05:00
|
|
|
|
2015-05-14 20:43:29 -05:00
|
|
|
args := c.RemainingArgs()
|
|
|
|
|
|
|
|
switch len(args) {
|
|
|
|
case 2:
|
2015-05-15 12:47:26 -05:00
|
|
|
rule = rewrite.NewSimpleRule(args[0], args[1])
|
|
|
|
simpleRules = append(simpleRules, rule)
|
|
|
|
case 1:
|
|
|
|
base = args[0]
|
|
|
|
fallthrough
|
|
|
|
case 0:
|
2015-05-14 20:43:29 -05:00
|
|
|
for c.NextBlock() {
|
|
|
|
switch c.Val() {
|
2015-05-15 12:47:26 -05:00
|
|
|
case "r", "regexp":
|
2015-05-14 20:43:29 -05:00
|
|
|
if !c.NextArg() {
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, c.ArgErr()
|
2015-05-14 20:43:29 -05:00
|
|
|
}
|
|
|
|
pattern = c.Val()
|
|
|
|
case "to":
|
|
|
|
if !c.NextArg() {
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, c.ArgErr()
|
2015-05-14 20:43:29 -05:00
|
|
|
}
|
|
|
|
to = c.Val()
|
|
|
|
case "ext":
|
|
|
|
args1 := c.RemainingArgs()
|
|
|
|
if len(args1) == 0 {
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, c.ArgErr()
|
2015-05-14 20:43:29 -05:00
|
|
|
}
|
|
|
|
ext = args1
|
|
|
|
default:
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, c.ArgErr()
|
2015-05-14 20:43:29 -05:00
|
|
|
}
|
|
|
|
}
|
2015-05-16 07:03:48 -05:00
|
|
|
// ensure pattern and to are specified
|
2015-05-14 20:43:29 -05:00
|
|
|
if pattern == "" || to == "" {
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, c.ArgErr()
|
2015-05-14 20:43:29 -05:00
|
|
|
}
|
|
|
|
if rule, err = rewrite.NewRegexpRule(base, pattern, to, ext); err != nil {
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, err
|
2015-05-14 20:43:29 -05:00
|
|
|
}
|
2015-05-15 12:47:26 -05:00
|
|
|
regexpRules = append(regexpRules, rule)
|
2015-05-14 20:43:29 -05:00
|
|
|
default:
|
2015-05-15 12:47:26 -05:00
|
|
|
return nil, c.ArgErr()
|
2015-05-04 12:04:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-05-15 12:47:26 -05:00
|
|
|
// put simple rules in front to avoid regexp computation for them
|
|
|
|
return append(simpleRules, regexpRules...), nil
|
2015-05-04 12:04:17 -05:00
|
|
|
}
|