-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmisc.go
More file actions
74 lines (64 loc) · 1.6 KB
/
Copy pathmisc.go
File metadata and controls
74 lines (64 loc) · 1.6 KB
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
package k
import (
"encoding/json"
"log"
"net"
"net/url"
"os"
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
// FIXME: Make Must* functions consistent
// MustURL calls net/url.Parse() and panics if it returns a non-nil
// error.
func MustURL(rawurl string) *url.URL {
u, err := url.Parse(rawurl)
if err != nil {
panic(err)
}
return u
}
// MustBytes is a function which usually wraps functions which return
// a byte slice and an error. It panics, if the given error is not nil.
func MustBytes(data []byte, err error) []byte {
if err != nil {
panic(err)
}
return data
}
// DefaultEnv returns the value of an environment variable, provided
// it has been set. If it is unset (i.e. empty), the specified default
// value is returned.
func DefaultEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
// MustTCPAddr calls net.ResolveTCPAddr and panics if it returns
// a non-nil error.
func MustTCPAddr(rawaddr string) *net.TCPAddr {
addr, err := net.ResolveTCPAddr("tcp", rawaddr)
if err != nil {
panic(err)
}
return addr
}
// Hostname returns def if no hostname could be determined
// for this machine, the machine's hostname otherwise.
func Hostname(def string) string {
if hostname, err := os.Hostname(); err == nil {
return hostname
}
return def
}
// JsonRemarshal takes old, marshals it into json and unmarshals it
// into new. If an error occurs along the way, it is returned.
func JsonRemarshal(new interface{}, old interface{}) error {
data, err := json.Marshal(old)
if err != nil {
return err
}
return json.Unmarshal(data, new)
}