/
helper.go
56 lines (48 loc) · 1.29 KB
/
helper.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
package config
import (
"os"
"strings"
"github.com/cezmunsta/ssh_ms/log"
"github.com/gabriel-vasile/mimetype"
)
const (
// FormatJSON will be used to indicate a JSON file
FormatJSON = uint(2)
// FormatText will be used to indicate a text file, or when an unknown mimetype is found
FormatText = uint(1)
// FormatUnknown will be used to indicate a problem
FormatUnknown = uint(0)
)
var formatLookup = map[string]uint{
"application/json": FormatJSON,
"default": FormatText,
}
func ensureDirExists(path string) (bool, error) {
if err := os.MkdirAll(NormalizePath(path), os.ModePerm); err != nil {
log.Errorf("Failed to create directory '%v': %v", path, err)
return false, err
}
return true, nil
}
// NormalizePath will handle the shell expansion of tilde
func NormalizePath(path string) string {
spath := path
if strings.HasPrefix(spath, "~") {
spath = strings.Replace(spath, "~", os.Getenv("HOME"), 1)
log.Debugf("Updated path %s to %s", path, spath)
}
return spath
}
// GetFileType will return the mimetype of a file
// fh : file handle
func GetFileType(fh *os.File) (uint, error) {
mt, err := mimetype.DetectFile(fh.Name())
if err != nil {
return FormatUnknown, err
}
ct, exists := formatLookup[mt.String()]
if !exists {
ct = formatLookup["default"]
}
return ct, nil
}