-
Notifications
You must be signed in to change notification settings - Fork 26
/
utils.go
77 lines (68 loc) · 1.65 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
package util
import (
"fmt"
"net/http"
netUrl "net/url"
"strings"
"time"
"unicode"
)
// UseTLSScheme returns url with https scheme if use is true
func UseTLSScheme(url string, use bool) (string, error) {
if url == "" {
return "", fmt.Errorf("empty URL")
}
if use {
urlObject, err := netUrl.Parse(url)
if err != nil {
return "", err
}
urlObject.Scheme = "https"
return urlObject.String(), nil
}
return url, nil
}
// NewHTTPClient creates a new instance of http.Client
func NewHTTPClient(timeout time.Duration, transport http.RoundTripper) *http.Client {
client := &http.Client{
Timeout: timeout,
}
if transport != nil {
client.Transport = transport
}
// go http client does not copy the headers when it follows the redirect.
// https://github.com/golang/go/issues/4800
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
for attr, val := range via[0].Header {
if _, ok := req.Header[attr]; !ok {
req.Header[attr] = val
}
}
return nil
}
return client
}
// IsInList returns true if item is in list
func IsInList(item string, l []string) bool {
for _, listItem := range l {
if item == listItem {
return true
}
}
return false
}
// SanitizeString will remove the first occurrence of a slash in a string and
// replaces all special characters with underscores.
func SanitizeString(s string) string {
trimmedLeftSlash := strings.TrimLeft(s, "/")
// replace all special characters with underscores
return strings.Map(func(r rune) rune {
switch {
case r == '_' || r == '-':
return r
case !unicode.IsDigit(r) && !unicode.IsLetter(r):
return '_'
}
return r
}, trimmedLeftSlash)
}