This repository was archived by the owner on Sep 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.go
222 lines (186 loc) · 4.58 KB
/
common.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"os"
"log"
"net/http"
"strconv"
"strings"
"errors"
"encoding/base64"
"bufio"
"io/ioutil"
"time"
)
/*
SYSTEM COMMON FUNCTIONS
This is a system function that put those we usually use function but not belongs to
any module / system.
E.g. fileExists / IsDir etc
*/
/*
Basic Response Functions
Send response with ease
*/
//Send text response with given w and message as string
func sendTextResponse(w http.ResponseWriter, msg string) {
w.Write([]byte(msg))
}
//Send JSON response, with an extra json header
func sendJSONResponse(w http.ResponseWriter, json string) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(json))
}
func sendErrorResponse(w http.ResponseWriter, errMsg string) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
}
func sendOK(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("\"OK\""))
}
/*
The paramter move function (mv)
You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
r (HTTP Request Object)
getParamter (string, aka $_GET['This string])
Will return
Paramter string (if any)
Error (if error)
*/
func mv(r *http.Request, getParamter string, postMode bool) (string, error) {
if postMode == false {
//Access the paramter via GET
keys, ok := r.URL.Query()[getParamter]
if !ok || len(keys[0]) < 1 {
//log.Println("Url Param " + getParamter +" is missing")
return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
}
// Query()["key"] will return an array of items,
// we only want the single item.
key := keys[0]
return string(key), nil
} else {
//Access the parameter via POST
r.ParseForm()
x := r.Form.Get(getParamter)
if len(x) == 0 || x == "" {
return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
}
return string(x), nil
}
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return true
}
func IsDir(path string) bool{
if (fileExists(path) == false){
return false
}
fi, err := os.Stat(path)
if err != nil {
log.Fatal(err)
return false
}
switch mode := fi.Mode(); {
case mode.IsDir():
return true
case mode.IsRegular():
return false
}
return false
}
func inArray(arr []string, str string) bool {
for _, a := range arr {
if a == str {
return true
}
}
return false
}
func timeToString(targetTime time.Time) string{
return targetTime.Format("2006-01-02 15:04:05")
}
func IntToString(number int) string{
return strconv.Itoa(number)
}
func StringToInt(number string) (int, error){
return strconv.Atoi(number)
}
func StringToInt64(number string) (int64, error){
i, err := strconv.ParseInt(number, 10, 64)
if err != nil {
return -1, err
}
return i, nil
}
func Int64ToString(number int64) string{
convedNumber:=strconv.FormatInt(number,10)
return convedNumber
}
func GetUnixTime() int64{
return time.Now().Unix()
}
func LoadImageAsBase64(filepath string) (string, error){
if !fileExists(filepath){
return "", errors.New("File not exists")
}
f, _ := os.Open(filepath)
reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
encoded := base64.StdEncoding.EncodeToString(content)
return string(encoded), nil
}
func PushToSliceIfNotExist(slice []string, newItem string) []string {
itemExists := false
for _, item := range slice{
if item == newItem{
itemExists = true
}
}
if !itemExists{
slice = append(slice, newItem)
}
return slice
}
func RemoveFromSliceIfExists(slice []string, target string) []string {
newSlice := []string{}
for _, item := range slice{
if item != target{
newSlice = append(newSlice, item)
}
}
return newSlice;
}
//Get the IP address of the current authentication user
func ReflectUserIP(w http.ResponseWriter, r *http.Request) {
requestPort,_ := mv(r, "port", false)
showPort := false;
if (requestPort == "true"){
//Show port as well
showPort = true;
}
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
if (!showPort){
IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
}
w.Write([]byte(IPAddress))
return;
}