-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.go
executable file
·194 lines (166 loc) · 4.98 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"sort"
"strings"
)
type Pair struct {
Key int
Value float64
}
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func SortMapKeysByValue(m map[int]float64) (sortedKeys []int) {
pl := make(PairList, len(m))
i := 0
for k, v := range m {
pl[i] = Pair{k, v}
i++
}
sortedKeys = make([]int, len(m))
sort.Sort(pl)
for i, k := range pl {
sortedKeys[i] = k.Key
}
return sortedKeys
}
var animals []string
var adjectives []string
func init() {
animalsText, _ := ioutil.ReadFile("static/data/animals")
animals = strings.Split(string(animalsText), ",")
adjectivesText, _ := ioutil.ReadFile("static/data/adjectives")
adjectives = strings.Split(string(adjectivesText), "\n")
}
func randomAlliterateCombo(seed int64) (combo string) {
s1 := rand.NewSource(seed)
r1 := rand.New(s1)
combo = ""
// generate random alliteration thats not been used
for {
animal := strings.Replace(strings.Title(animals[r1.Intn(len(animals)-1)]), " ", "", -1)
adjective := strings.Replace(strings.Title(adjectives[r1.Intn(len(adjectives)-1)]), " ", "", -1)
if animal[0] == adjective[0] && len(animal)+len(adjective) < 18 { //&& stringInSlice(strings.ToLower(adjective+animal), takenNames) == false {
combo = adjective + animal
break
}
}
return
}
// GetClientIPHelper gets the client IP using a mixture of techniques.
// This is how it is with golang at the moment.
func GetClientIPHelper(req *http.Request) (ipResult string, errResult error) {
// Try lots of ways :) Order is important.
// Try Request Headers (X-Forwarder). Client could be behind a Proxy
ip, err := getClientIPByHeaders(req)
if err == nil {
log.Printf("debug: Found IP using Request Headers sniffing. ip: %v", ip)
return ip, nil
}
// Try by Request
ip, err = getClientIPByRequestRemoteAddr(req)
if err == nil {
log.Printf("debug: Found IP using Request sniffing. ip: %v", ip)
return ip, nil
}
// Try Request Header ("Origin")
url, err := url.Parse(req.Header.Get("Origin"))
if err == nil {
host := url.Host
ip, _, err := net.SplitHostPort(host)
if err == nil {
log.Printf("debug: Found IP using Header (Origin) sniffing. ip: %v", ip)
return ip, nil
}
}
err = errors.New("error: Could not find clients IP address")
return "", err
}
// getClientIPByRequest tries to get directly from the Request.
// https://blog.golang.org/context/userip/userip.go
func getClientIPByRequestRemoteAddr(req *http.Request) (ip string, err error) {
// Try via request
ip, port, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
log.Printf("debug: Getting req.RemoteAddr %v", err)
return "", err
} else {
log.Printf("debug: With req.RemoteAddr found IP:%v; Port: %v", ip, port)
}
userIP := net.ParseIP(ip)
if userIP == nil {
message := fmt.Sprintf("debug: Parsing IP from Request.RemoteAddr got nothing.")
log.Printf(message)
return "", fmt.Errorf(message)
}
log.Printf("debug: Found IP: %v", userIP)
return userIP.String(), nil
}
// getClientIPByHeaders tries to get directly from the Request Headers.
// This is only way when the client is behind a Proxy.
func getClientIPByHeaders(req *http.Request) (ip string, err error) {
// Client could be behid a Proxy, so Try Request Headers (X-Forwarder)
ipSlice := []string{}
ipSlice = append(ipSlice, req.Header.Get("X-Forwarded-For"))
ipSlice = append(ipSlice, req.Header.Get("x-forwarded-for"))
ipSlice = append(ipSlice, req.Header.Get("X-FORWARDED-FOR"))
for _, v := range ipSlice {
log.Printf("debug: client request header check gives ip: %v", v)
if v != "" {
return v, nil
}
}
err = errors.New("error: Could not find clients IP address from the Request Headers")
return "", err
}
// getMyInterfaceAddr gets this private network IP. Basically the Servers IP.
func getMyInterfaceAddr() (net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
addresses := []net.IP{}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
addresses = append(addresses, ip)
}
}
if len(addresses) == 0 {
return nil, fmt.Errorf("no address Found, net.InterfaceAddrs: %v", addresses)
}
//only need first
return addresses[0], nil
}