/
util.go
69 lines (64 loc) · 1.46 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
package httploader
import (
"math/rand"
"net/http"
"net/url"
"path"
"strings"
)
func randomProxyFunc(proxyURLs, hosts string) func(*http.Request) (*url.URL, error) {
var urls []*url.URL
var allowedSources []AllowedSource
for _, split := range strings.Split(proxyURLs, ",") {
if u, err := url.Parse(strings.TrimSpace(split)); err == nil {
urls = append(urls, u)
}
}
ln := len(urls)
for _, host := range strings.Split(hosts, ",") {
host = strings.TrimSpace(host)
if len(host) > 0 {
allowedSources = append(allowedSources, NewHostPatternAllowedSource(host))
}
}
return func(r *http.Request) (u *url.URL, err error) {
if len(urls) == 0 {
return
}
if !isURLAllowed(r.URL, allowedSources) {
return
}
u = urls[rand.Intn(ln)]
return
}
}
func isURLAllowed(u *url.URL, allowedSources []AllowedSource) bool {
if len(allowedSources) == 0 {
return true
}
for _, source := range allowedSources {
if source.Match(u) {
return true
}
}
return false
}
func parseContentType(contentType string) string {
idx := strings.Index(contentType, ";")
if idx == -1 {
idx = len(contentType)
}
return strings.TrimSpace(strings.ToLower(contentType[0:idx]))
}
func validateContentType(contentType string, accepts []string) bool {
if len(accepts) == 0 {
return true
}
contentType = parseContentType(contentType)
for _, accept := range accepts {
if ok, err := path.Match(accept, contentType); ok && err == nil {
return true
}
}
return false
}