2015-09-30 12:37:10 -05:00
|
|
|
package setup
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
|
|
"github.com/mholt/caddy/middleware/mime"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Mime configures a new mime middleware instance.
|
|
|
|
func Mime(c *Controller) (middleware.Middleware, error) {
|
|
|
|
configs, err := mimeParse(c)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(next middleware.Handler) middleware.Handler {
|
|
|
|
return mime.Mime{Next: next, Configs: configs}
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2016-03-16 01:11:19 -05:00
|
|
|
func mimeParse(c *Controller) (mime.Config, error) {
|
|
|
|
configs := mime.Config{}
|
2015-09-30 12:37:10 -05:00
|
|
|
|
|
|
|
for c.Next() {
|
|
|
|
// At least one extension is required
|
|
|
|
|
|
|
|
args := c.RemainingArgs()
|
|
|
|
switch len(args) {
|
|
|
|
case 2:
|
2016-03-16 01:11:19 -05:00
|
|
|
if err := validateExt(configs, args[0]); err != nil {
|
2015-09-30 12:37:10 -05:00
|
|
|
return configs, err
|
|
|
|
}
|
2016-03-16 01:11:19 -05:00
|
|
|
configs[args[0]] = args[1]
|
2015-09-30 12:37:10 -05:00
|
|
|
case 1:
|
|
|
|
return configs, c.ArgErr()
|
|
|
|
case 0:
|
|
|
|
for c.NextBlock() {
|
|
|
|
ext := c.Val()
|
2016-03-16 01:11:19 -05:00
|
|
|
if err := validateExt(configs, ext); err != nil {
|
2015-09-30 12:37:10 -05:00
|
|
|
return configs, err
|
|
|
|
}
|
|
|
|
if !c.NextArg() {
|
|
|
|
return configs, c.ArgErr()
|
|
|
|
}
|
2016-03-16 01:11:19 -05:00
|
|
|
configs[ext] = c.Val()
|
2015-09-30 12:37:10 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return configs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// validateExt checks for valid file name extension.
|
2016-03-16 01:11:19 -05:00
|
|
|
func validateExt(configs mime.Config, ext string) error {
|
2015-09-30 12:37:10 -05:00
|
|
|
if !strings.HasPrefix(ext, ".") {
|
|
|
|
return fmt.Errorf(`mime: invalid extension "%v" (must start with dot)`, ext)
|
|
|
|
}
|
2016-03-16 01:11:19 -05:00
|
|
|
if _, ok := configs[ext]; ok {
|
|
|
|
return fmt.Errorf(`mime: duplicate extension "%v" found`, ext)
|
|
|
|
}
|
2015-09-30 12:37:10 -05:00
|
|
|
return nil
|
|
|
|
}
|