-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhelper.go
45 lines (38 loc) · 952 Bytes
/
helper.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
package utils
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
func Message(status bool, message string) map[string]interface{} {
return map[string]interface{}{"status": status, "message": message}
}
func Respond(w http.ResponseWriter, data map[string]interface{}) {
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
func GetUserIpAddress(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
ipAndPortPart := strings.Split(IPAddress, ":")
if len(ipAndPortPart) > 0 {
IPAddress = ipAndPortPart[0]
}
return IPAddress
}
func GetUserAgent(r *http.Request) string {
return r.Header.Get("User-Agent")
}
func MustGetEnv(key string) string {
if val := os.Getenv(key); "" != val {
return val
}
panic(fmt.Sprintf("environment variable %s unset", key))
}