forked from lieuwex/whapp-irc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
68 lines (55 loc) · 1.12 KB
/
util.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
package main
import (
"mime"
"os"
"os/signal"
"regexp"
"strconv"
"time"
"github.com/h2non/filetype"
"github.com/mozillazg/go-unidecode"
)
func strTimestamp() string {
return strconv.FormatInt(time.Now().UnixNano(), 10)
}
func getExtension(bytes []byte) string {
typ, err := filetype.Match(bytes)
if err != nil {
return ""
}
res := typ.Extension
if res == "unknown" {
return ""
}
return res
}
func getExtensionByMime(typ string) (string, error) {
extensions, err := mime.ExtensionsByType(typ)
if err != nil {
return "", err
}
if len(extensions) == 0 {
return "", nil
}
return extensions[0][1:], nil
}
func getExtensionByMimeOrBytes(mime string, bytes []byte) string {
if res, err := getExtensionByMime(mime); res != "" && err == nil {
return res
}
return getExtension(bytes)
}
var unsafeRegex = regexp.MustCompile(`(?i)[^a-z\d+]`)
func ircSafeString(str string) string {
str = unidecode.Unidecode(str)
return unsafeRegex.ReplaceAllLiteralString(str, "")
}
func onInterrupt(fn func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
fn()
os.Exit(1)
}()
}