This repository has been archived by the owner on Jun 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
util.go
118 lines (95 loc) · 2.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
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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"unicode"
)
// CommandError is the checked exception thrown on runtime errors
type CommandError struct {
msg string // description of error
err error // inner error
}
func (e *CommandError) Error() string { return e.msg }
// Panics with a message if the given error isn't nil
func check(err error, a ...interface{}) {
if err != nil {
var msg string
if len(a) > 0 {
msg = fmt.Sprintf("%s (%s)", fmt.Sprintf(a[0].(string), a[1:]...), err)
} else {
msg = fmt.Sprintf("%s", err)
}
panic(&CommandError{msg, err})
}
}
// Panics with a message if the given condition isn't true
func assertThat(condition bool, msg string, a ...interface{}) {
if !condition {
panic(&CommandError{fmt.Sprintf(msg, a...), nil})
}
}
// Min value
func min(a int, b int) int {
if a < b {
return a
}
return b
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func ellipsis(input string, maxLength int) string {
trimmed := strings.TrimSpace(input)
if len(trimmed) > maxLength {
return fmt.Sprintf("%s...", strings.TrimSpace(trimmed[0:max(maxLength-3, 0)]))
}
return trimmed
}
func defaults(a ...string) string {
for _, item := range a {
if len(item) > 0 {
return item
}
}
return ""
}
// Strip whitespace from string
func stripWhitespace(a string) string {
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, a)
}
func httpReadBody(response *http.Response) ([]byte, error) {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, fmt.Errorf("HTTP %d Error: %s", response.StatusCode, ellipsis(string(body), 256))
}
return body, nil
}
func httpPostForm(url string, values url.Values) ([]byte, error) {
response, err := http.PostForm(url, values)
if err != nil {
return nil, err
}
return httpReadBody(response)
}
func httpGet(url string) ([]byte, error) {
response, err := http.Get(url)
if err != nil {
return nil, err
}
return httpReadBody(response)
}