forked from aldelo/common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
95 lines (83 loc) · 2.33 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
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
package helper
/*
* Copyright 2020 Aldelo, LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import (
"fmt"
"github.com/google/uuid"
"net"
"os"
"strings"
"time"
)
// GetNetListener triggers the specified port to listen via tcp
func GetNetListener(port uint) (net.Listener, error) {
if l, e := net.Listen("tcp", fmt.Sprintf(":%d", port)); e != nil {
return nil, fmt.Errorf("Listen Tcp on Port %d Failed: %v", port, e)
} else {
return l, nil
}
}
// GetLocalIP returns the first non loopback ip
func GetLocalIP() string {
if addrs, err := net.InterfaceAddrs(); err != nil {
return ""
} else {
for _, a := range addrs {
if ip, ok := a.(*net.IPNet); ok && !ip.IP.IsLoopback() && !ip.IP.IsInterfaceLocalMulticast() && !ip.IP.IsLinkLocalMulticast() && !ip.IP.IsLinkLocalUnicast() && !ip.IP.IsMulticast() && !ip.IP.IsUnspecified() {
if ip.IP.To4() != nil {
return ip.IP.String()
}
}
}
return ""
}
}
// LenTrim returns length of space trimmed string s
func LenTrim(s string) int {
return len(strings.TrimSpace(s))
}
// IntPtr casts int to int pointer
func IntPtr(i int) *int {
return &i
}
// DurationPtr casts Duration to Duration pointer
func DurationPtr(d time.Duration) *time.Duration {
return &d
}
// GenerateUUIDv4 will generate a UUID Version 4 (Random) to represent a globally unique identifier (extremely rare chance of collision)
func GenerateUUIDv4() (string, error) {
id, err := uuid.NewRandom()
if err != nil {
// error
return "", err
} else {
// has id
return id.String(), nil
}
}
// NewUUID will generate a UUID Version 4 (Random) and ignore error if any
func NewUUID() string {
id, _ := GenerateUUIDv4()
return id
}
// FileExists checks if input file in path exists
func FileExists(path string) bool {
if _, err := os.Stat(path); err == nil {
return true
} else {
return false
}
}