caddy/config/setup/rewrite.go

80 lines
1.7 KiB
Go
Raw Normal View History

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-16 01:47:26 +08:00
var simpleRules []rewrite.Rule
var regexpRules []rewrite.Rule
for c.Next() {
var rule rewrite.Rule
var err error
2015-05-16 01:47:26 +08:00
var base = "/"
var pattern, to string
var ext []string
args := c.RemainingArgs()
switch len(args) {
case 2:
2015-05-16 01:47:26 +08:00
rule = rewrite.NewSimpleRule(args[0], args[1])
simpleRules = append(simpleRules, rule)
case 1:
base = args[0]
fallthrough
case 0:
for c.NextBlock() {
switch c.Val() {
2015-05-16 01:47:26 +08:00
case "r", "regexp":
if !c.NextArg() {
2015-05-16 01:47:26 +08:00
return nil, c.ArgErr()
}
pattern = c.Val()
case "to":
if !c.NextArg() {
2015-05-16 01:47:26 +08:00
return nil, c.ArgErr()
}
to = c.Val()
case "ext":
args1 := c.RemainingArgs()
if len(args1) == 0 {
2015-05-16 01:47:26 +08:00
return nil, c.ArgErr()
}
ext = args1
default:
2015-05-16 01:47:26 +08:00
return nil, c.ArgErr()
}
}
// ensure pattern and to are specified
if pattern == "" || to == "" {
2015-05-16 01:47:26 +08:00
return nil, c.ArgErr()
}
if rule, err = rewrite.NewRegexpRule(base, pattern, to, ext); err != nil {
2015-05-16 01:47:26 +08:00
return nil, err
}
2015-05-16 01:47:26 +08:00
regexpRules = append(regexpRules, rule)
default:
2015-05-16 01:47:26 +08:00
return nil, c.ArgErr()
}
}
2015-05-16 01:47:26 +08:00
// put simple rules in front to avoid regexp computation for them
return append(simpleRules, regexpRules...), nil
}