-
Notifications
You must be signed in to change notification settings - Fork 7
/
helpers.go
97 lines (82 loc) · 1.91 KB
/
helpers.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
// Copyright 2016 Nevio Vesic
// Please check out LICENSE file for more information about limitations
// MIT License
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"math/rand"
"net/http"
"strconv"
"time"
disposable "github.com/0x19/disposable/protos"
uuid "github.com/satori/go.uuid"
)
// GetExternalIP - Will check and get current machine external IP address
func GetExternalIP() (string, error) {
rsp, err := http.Get("http://checkip.amazonaws.com")
if err != nil {
return "", err
}
defer rsp.Body.Close()
buf, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(buf)), nil
}
// StringInSlice - Will check if string in list. This is equivalent to python if x in []
func StringInSlice(str string, list []string) bool {
for _, value := range list {
if value == str {
return true
}
}
return false
}
// DecodeJSONBody -
func DecodeJSONBody(model interface{}, rc io.ReadCloser) error {
decoder := json.NewDecoder(rc)
if err := decoder.Decode(model); err != nil {
return err
}
return nil
}
// DecodeRequestBody -
func DecodeRequestBody(i interface{}, body io.Reader) *disposable.DisposableResponse {
decoder := json.NewDecoder(body)
if err := decoder.Decode(i); err != nil {
return &disposable.DisposableResponse{
Status: false,
RequestId: GetUUID(),
Error: &disposable.Error{
Message: ErrorJSONParseError,
Type: TypeJSONParseError,
Info: map[string]string{
"error": err.Error(),
},
},
}
}
return nil
}
// ToBool - Will return string value back as bool OR respond with defaults
func ToBool(value string, def bool) bool {
b, err := strconv.ParseBool(value)
if err != nil {
return def
}
return b
}
// Random -
func Random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
// GetUUID -
func GetUUID() string {
udidv4, _ := uuid.NewV4()
return udidv4.String()
}