/
utils.go
117 lines (92 loc) · 1.94 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
package tracking
import (
"bufio"
"encoding/json"
"io/ioutil"
"math/rand"
"os"
"time"
"strings"
"github.com/joaosoft/errors"
"github.com/oklog/ulid"
)
func getEnv() string {
env := os.Getenv("env")
if env == "" {
env = "local"
}
return env
}
func exists(file string) bool {
if _, err := os.Stat(file); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func readFile(file string, obj interface{}) ([]byte, error) {
var err error
if !exists(file) {
return nil, errors.New(errors.ErrorLevel, 0, "file don't exist")
}
f, err := os.Open(file)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
if obj != nil {
if err := json.Unmarshal(data, obj); err != nil {
return nil, err
}
}
return data, nil
}
func readFileLines(file string) ([]string, error) {
lines := make([]string, 0)
if !exists(file) {
return nil, errors.New(errors.ErrorLevel, 0, "file don't exist")
}
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
func writeFile(file string, obj interface{}) error {
if !exists(file) {
return errors.New(errors.ErrorLevel, 0, "file don't exist")
}
jsonBytes, _ := json.MarshalIndent(obj, "", " ")
if err := ioutil.WriteFile(file, jsonBytes, 0644); err != nil {
return err
}
return nil
}
func encodeString(s string) string {
// http://www.postgresql.org/docs/9.2/static/sql-syntax-lexical.html
return `'` + strings.Replace(s, `'`, `''`, -1) + `'`
}
func genUI() string {
t := time.Now().UTC()
entropy := rand.New(rand.NewSource(t.UnixNano()))
id := ulid.MustNew(ulid.Timestamp(t), entropy)
return id.String()
}
func valUI(id string) bool {
if _, err := ulid.Parse(id); err != nil {
return false
}
return true
}