-
Notifications
You must be signed in to change notification settings - Fork 0
/
ext.go
71 lines (56 loc) · 1.16 KB
/
ext.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
package extensions
import (
"errors"
"strings"
"sync"
)
var (
// UnsupportedExt is used for unsupported file extension
UnsupportedExt = Ext{Supported: false, FileType: FileTypeUnsupported}
errUnsupportedExt = errors.New("unsupported extension")
)
type extensions struct {
exts map[string]Ext
mut *sync.RWMutex
}
func (e *extensions) add(ext Ext) {
e.mut.Lock()
defer e.mut.Unlock()
e.exts[ext.Ext] = ext
}
func (e *extensions) get(ext string) (Ext, error) {
e.mut.RLock()
defer e.mut.RUnlock()
res, ok := e.exts[ext]
if !ok {
return Ext{}, errUnsupportedExt
}
return res, nil
}
var allExtensions extensions
func init() {
allExtensions = extensions{
exts: make(map[string]Ext),
mut: new(sync.RWMutex),
}
for i := range extensionsList {
allExtensions.add(extensionsList[i])
}
}
// GetExt returns Ext according to passed file ext.
// If there's no such extension, it returns UnsupportedExt
func GetExt(ext string) Ext {
if len(ext) == 0 {
return UnsupportedExt
}
ext = strings.ToLower(ext)
if ext[0] != '.' {
ext = "." + ext
}
res, err := allExtensions.get(ext)
if err != nil {
res = UnsupportedExt
res.Ext = ext
}
return res
}