0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-23 22:27:38 -05:00
caddy/caddy/setup/mime.go

66 lines
1.3 KiB
Go
Raw Normal View History

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
}
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:
if err := validateExt(configs, args[0]); err != nil {
2015-09-30 12:37:10 -05:00
return configs, err
}
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()
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()
}
configs[ext] = c.Val()
2015-09-30 12:37:10 -05:00
}
}
}
return configs, nil
}
// validateExt checks for valid file name extension.
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)
}
if _, ok := configs[ext]; ok {
return fmt.Errorf(`mime: duplicate extension "%v" found`, ext)
}
2015-09-30 12:37:10 -05:00
return nil
}