forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathadmin.go
More file actions
268 lines (243 loc) · 5.47 KB
/
admin.go
File metadata and controls
268 lines (243 loc) · 5.47 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package uadmin
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"golang.org/x/net/html"
)
/*
admin Tags
read_only:TRUE
email:TRUE
hidden:TRUE
html:TRUE
fk:"ModelName"
list:TRUE
list_filter:TRUE
search:TRUE
dontCache:TRUE
required:TRUE
help:TRUE
pattern:TRUE
pattern_msg:"Message"
max:"int"
min:"int"
link:TRUE
file:TRUE
dependsOn:""
linkerObj:""
linkerParentField:""
linkerChildField:""
childObj:""
upload_to:"path"
code:"true"
money:"true" use on float
defaultValue:""
*/
// commaf is a function to format number with thousand separator
// and two decimal points
func commaf(j interface{}) string {
v, _ := strconv.ParseFloat(fmt.Sprint(j), 64)
buf := &bytes.Buffer{}
if v < 0 {
buf.Write([]byte{'-'})
v = 0 - v
}
s := fmt.Sprintf("%.2f", v)
comma := []byte{','}
parts := strings.Split(s, ".")
pos := 0
if len(parts[0])%3 != 0 {
pos += len(parts[0]) % 3
buf.WriteString(parts[0][:pos])
buf.Write(comma)
}
for ; pos < len(parts[0]); pos += 3 {
buf.WriteString(parts[0][pos : pos+3])
buf.Write(comma)
}
buf.Truncate(buf.Len() - 1)
if len(parts) > 1 {
buf.Write([]byte{'.'})
buf.WriteString(parts[1])
}
return buf.String()
}
func isLocal(Addr string) bool {
if strings.Contains(Addr, ":") && !strings.Contains(Addr, ".") {
Addr = strings.TrimPrefix(Addr, "[")
if strings.HasPrefix(Addr, "::") || strings.HasPrefix(Addr, "fc") || strings.HasPrefix(Addr, "fd") {
return true
}
}
p := strings.Split(strings.Split(Addr, ":")[0], ".")
if len(p) != 4 {
return false
}
_, err := strconv.ParseInt(p[2], 10, 64)
if err != nil {
return false
}
_, err = strconv.ParseInt(p[3], 10, 64)
if err != nil {
return false
}
v1, err := strconv.ParseInt(p[0], 10, 64)
if err != nil {
return false
}
v2, err := strconv.ParseInt(p[1], 10, 64)
if err != nil {
return false
}
if v1 == 10 {
return true
}
if v1 == 172 {
if v2 >= 16 && v2 <= 31 {
return true
}
}
if v1 == 192 && v2 == 168 {
return true
}
if v1 == 127 {
return true
}
return false
}
// saver is an interface to deal with form froms
type saver interface {
Save()
}
// counter !
type counter interface {
Count(interface{}, interface{}, ...interface{}) int
}
type adminPager interface {
AdminPage(string, bool, int, int, interface{}, interface{}, ...interface{}) error
}
func paginationHandler(itemCount int, PageLength int) (i int) {
pCount := (float64(itemCount) / float64(PageLength))
if pCount > float64(int(pCount)) {
pCount++
}
i = int(pCount)
if i == 1 {
i--
}
return i
}
// toSnakeCase !
func toSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
// JSONMarshal Generates JSON format from an object
func JSONMarshal(v interface{}, safeEncoding bool) ([]byte, error) {
// b, err := json.Marshal(v)
b, err := jsonMarshal(v)
if safeEncoding {
b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
}
return b, err
}
func nullZeroValueStructs(record map[string]interface{}) map[string]interface{} {
for k := range record {
switch v := record[k].(type) {
case map[string]interface{}:
if id, ok := v["ID"].(float64); ok && id == 0 {
record[k] = nil
} else if id, ok := v["id"].(float64); ok && id == 0 {
record[k] = nil
} else {
record[k] = nullZeroValueStructs(v)
}
}
}
return record
}
func removeZeroValueStructs(buf []byte) []byte {
response := map[string]interface{}{}
json.Unmarshal(buf, &response)
if val, ok := response["result"].(map[string]interface{}); ok {
val = nullZeroValueStructs(val)
buf, _ = json.Marshal(val)
return buf
}
if _, ok := response["result"].([]interface{}); !ok {
return buf
}
val := response["result"].([]interface{})
var record map[string]interface{}
for i := range val {
record = val[i].(map[string]interface{})
record = nullZeroValueStructs(record)
val[i] = record
}
response["result"] = val
buf, _ = json.Marshal(response)
return buf
}
func jsonMarshal(v interface{}) ([]byte, error) {
var buf []byte
var err error
if CompressJSON {
buf, err = json.Marshal(v)
if err == nil && RemoveZeroValueJSON {
buf = removeZeroValueStructs(buf)
}
} else {
buf, err = json.MarshalIndent(v, "", " ")
}
return buf, err
}
// ReturnJSON returns json to the client
func ReturnJSON(w http.ResponseWriter, r *http.Request, v interface{}) {
// Set content type in header
w.Header().Set("Content-Type", "application/json")
// Marshal content
b, err := jsonMarshal(v)
if err != nil {
response := map[string]interface{}{
"status": "error",
"error_msg": fmt.Sprintf("unable to encode JSON. %s", err),
}
b, _ = jsonMarshal(response)
w.Write(b)
return
}
if CustomizeJSON != nil {
b = CustomizeJSON(w, r, v, b)
}
w.Write(b)
}
func stripHTMLScriptTag(v string) string {
doc, err := html.Parse(strings.NewReader(v))
if err != nil {
return ""
}
removeScript(doc)
b := bytes.NewBuffer([]byte{})
if err := html.Render(b, doc); err != nil {
return ""
}
return b.String()
}
func removeScript(n *html.Node) {
// if note is script tag
if n.Type == html.ElementNode && (strings.Contains(n.Data, "script") || strings.Contains(n.Data, "frame")) {
n.Parent.RemoveChild(n)
return // script tag is gone...
}
// traverse DOM
for c := n.FirstChild; c != nil; c = c.NextSibling {
removeScript(c)
}
}