-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.go
115 lines (103 loc) · 1.85 KB
/
utils.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
package main
import (
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/webx-top/com"
)
var (
selfPath string
selfDir string
)
func SelfPath() string {
if len(selfPath) == 0 {
selfPath, _ = filepath.Abs(os.Args[0])
}
return selfPath
}
func SelfDir() string {
if len(selfDir) == 0 {
selfDir = filepath.Dir(SelfPath())
}
return selfDir
}
func dialAddress(address string, timeOut int, args ...func() bool) (err error) {
var fn func() bool
if len(args) > 0 {
fn = args[0]
}
ticker := time.NewTicker(1 * time.Second)
defer func() {
ticker.Stop()
}()
startTime := time.Now()
timeoutDur := time.Duration(timeOut) * time.Second
for range ticker.C {
conn, err := net.DialTimeout("tcp", address, timeoutDur)
if err == nil {
conn.Close()
return err
}
if fn != nil && !fn() {
return nil
}
if time.Now().After(startTime.Add(timeoutDur)) {
return fmt.Errorf(`failed to listen on %s: %w`, address, err)
}
}
return err
}
func isFreePort(port string) bool {
conn, err := net.Dial("tcp", "127.0.0.1:"+port)
if err == nil {
conn.Close()
return true
}
return false
}
func mustSuccess(err error) {
if err != nil {
panic(err.Error())
}
}
func quickSort(arr []int64, start, end int) {
if start < end {
i, j := start, end
key := arr[(start+end)/2]
for i <= j {
for arr[i] < key {
i++
}
for arr[j] > key {
j--
}
if i <= j {
arr[i], arr[j] = arr[j], arr[i]
i++
j--
}
}
if start < j {
quickSort(arr, start, j)
}
if end > i {
quickSort(arr, i, end)
}
}
}
func parseParams(param string) []string {
if param[0] != ':' {
return com.ParseArgs(param)
}
//:<分割符>:<参数>
delim := ` `
param = strings.TrimPrefix(param, `:`)
if pos := strings.Index(param, `:`); pos > 0 {
delim = param[0:pos]
param = param[pos+1:]
}
return strings.Split(param, delim)
}