-
Notifications
You must be signed in to change notification settings - Fork 6
/
util.go
125 lines (109 loc) Β· 2.36 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"errors"
"fmt"
"gopkg.in/mattn/go-runewidth.v0"
"mime"
"net/http"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
)
const (
kib = 1024
mib = 1048576
gib = 1073741824
tib = 1099511627776
)
func formatBytes(i int64) (result string) {
switch {
case i >= tib:
result = fmt.Sprintf("%6.2fTB", float64(i)/tib)
case i >= gib:
result = fmt.Sprintf("%6.2fGB", float64(i)/gib)
case i >= mib:
result = fmt.Sprintf("%6.2fMB", float64(i)/mib)
case i >= kib:
result = fmt.Sprintf("%6.2fKB", float64(i)/kib)
default:
result = fmt.Sprintf("%7dB", i)
}
if len(result)>8{
result=strings.Join([]string{result[:6],result[7:]},"")
}
return
}
func formatTime(i int64) string {
if i < 60 {
return fmt.Sprintf("%2ds", i)
} else if i < 3600 {
s := i % 60
m := i / 60
if s == 0 {
return fmt.Sprintf("%2dm", m)
} else {
return fmt.Sprintf("%2dm", m) + formatTime(s)
}
} else {
s := i % 3600
h := i / 3600
if s == 0 {
return fmt.Sprintf("%2dh", h)
} else {
return fmt.Sprintf("%2dh", h) + formatTime(s)
}
}
}
var errNoFilename = errors.New("no filename could be determined")
func guessFilename(resp *http.Response) (string, error) {
filename := resp.Request.URL.Path
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
filename = params["filename"]
}
}
if filename == "" || strings.HasSuffix(filename, "/") || strings.Contains(filename, "\x00") {
return "", errNoFilename
}
filename = filepath.Base(path.Clean("/" + filename))
if filename == "" || filename == "." || filename == "/" {
return "", errNoFilename
}
return filename, nil
}
var ctrlFinder = regexp.MustCompile("\x1b\x5b[0-9]+\x6d")
func cellCount(s string) int {
n := runewidth.StringWidth(s)
for _, sm := range ctrlFinder.FindAllString(s, -1) {
n -= runewidth.StringWidth(sm)
}
return n
}
func getLimitFromUrl(url string) (int64, string) {
s := strings.Split(url, ":")
if len(s) >= 2 {
i, err := strconv.ParseInt(s[0], 0, 0)
if err != nil {
return -1, url
} else {
return i, strings.Join(s[1:], ":")
}
}
return -1, url
}
func parseHeaderFromStringSlice(h []string) (m map[string]string){
if h==nil {
m=nil
return
}
m=make(map[string]string)
for _,ss:=range h{
if strings.Contains(ss,":"){
s:=strings.Split(ss,":")
m[s[0]]=s[1]
}
}
return
}