generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
mime.go
99 lines (79 loc) · 2.28 KB
/
mime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package mime
import (
"bufio"
"os"
"path/filepath"
"strings"
echo "github.com/datumforge/echox"
"github.com/datumforge/echox/middleware"
)
// Config defines the config for Mime middleware
type Config struct {
// Enabled indicates if the mime middleware should be enabled
Enabled bool `json:"enabled" koanf:"enabled" default:"true"`
// Skipper defines a function to skip middleware
Skipper middleware.Skipper `json:"-" koanf:"-"`
// MimeTypesFile is the file to load mime types from
MimeTypesFile string `json:"mimeTypesFile" koanf:"mimeTypesFile" default:""`
// DefaultContentType is the default content type to set if no mime type is found
DefaultContentType string `json:"defaultContentType" koanf:"defaultContentType" default:"application/data"`
}
// DefaultConfig is the default Gzip middleware config.
var DefaultConfig = Config{
Skipper: middleware.DefaultSkipper,
MimeTypesFile: "",
DefaultContentType: "application/data",
}
// New creates a new middleware function with the default config
func New() echo.MiddlewareFunc {
return NewWithConfig(DefaultConfig)
}
// NewWithConfig creates a new middleware function with the provided config
func NewWithConfig(config Config) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultConfig.Skipper
}
mimeTypes := loadMimeFile(config.MimeTypesFile)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
ext := filepath.Ext(c.Request().URL.Path)
mimeType := mimeTypes[ext]
if mimeType == "" {
mimeType = config.DefaultContentType
}
if mimeType != "" {
c.Response().Header().Set(echo.HeaderContentType, mimeType)
}
return next(c)
}
}
}
func loadMimeFile(filename string) map[string]string {
mimeTypes := make(map[string]string)
f, err := os.Open(filename)
if err != nil {
return mimeTypes
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) <= 1 || fields[0][0] == '#' {
continue
}
mimeType := fields[0]
for _, ext := range fields[1:] {
if ext[0] == '#' {
break
}
mimeTypes[ext] = mimeType
}
}
if err := scanner.Err(); err != nil {
return mimeTypes
}
return mimeTypes
}