-
Notifications
You must be signed in to change notification settings - Fork 116
/
utils.go
95 lines (79 loc) · 1.86 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
package boringproxy
import (
"crypto/rand"
"encoding/json"
"errors"
"io/ioutil"
"math/big"
"net"
"net/http"
"strconv"
"strings"
)
func saveJson(data interface{}, filePath string) error {
jsonStr, err := json.MarshalIndent(data, "", " ")
if err != nil {
return errors.New("Error serializing JSON")
} else {
err := ioutil.WriteFile(filePath, jsonStr, 0644)
if err != nil {
return errors.New("Error saving JSON")
}
}
return nil
}
// Looks for auth token in query string, then headers, then cookies
func extractToken(tokenName string, r *http.Request) (string, error) {
query := r.URL.Query()
queryToken := query.Get(tokenName)
if queryToken != "" {
return queryToken, nil
}
tokenHeader := r.Header.Get(tokenName)
if tokenHeader != "" {
return tokenHeader, nil
}
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
tokenHeader := strings.Split(authHeader, " ")[1]
return tokenHeader, nil
}
tokenCookie, err := r.Cookie(tokenName)
if err == nil {
return tokenCookie.Value, nil
}
return "", errors.New("No token found")
}
const chars string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func genRandomCode(length int) (string, error) {
id := ""
for i := 0; i < length; i++ {
randIndex, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return "", err
}
id += string(chars[randIndex.Int64()])
}
return id, nil
}
func randomOpenPort() (int, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
addrParts := strings.Split(listener.Addr().String(), ":")
port, err := strconv.Atoi(addrParts[len(addrParts)-1])
if err != nil {
return 0, err
}
listener.Close()
return port, nil
}
func stringInArray(value string, array []string) bool {
for _, item := range array {
if item == value {
return true
}
}
return false
}