forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd_api_method.go
67 lines (57 loc) · 1.41 KB
/
d_api_method.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
package uadmin
import (
"fmt"
"net/http"
"reflect"
"strings"
)
func dAPIMethodHandler(w http.ResponseWriter, r *http.Request, s *Session) {
urlParts := strings.Split(r.URL.Path, "/")
modelName := urlParts[0]
model, _ := NewModel(modelName, true)
params := getURLArgs(r)
if len(urlParts) < 4 {
w.WriteHeader(400)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Bad request, URL format should be api/d/model/method/{METHOD_NAME}/{ID}",
})
return
}
if CheckCSRF(r) {
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Failed CSRF protection.",
})
return
}
f := model.MethodByName(urlParts[2])
if !f.IsValid() {
f = model.Elem().MethodByName(urlParts[2])
}
if !f.IsValid() {
w.WriteHeader(404)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Method (" + urlParts[2] + ") doesn't exist.",
})
return
}
Get(model.Interface(), "id = ?", urlParts[3])
if GetID(model) == 0 {
w.WriteHeader(404)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "ID doesn't exist (" + urlParts[3] + ").",
})
return
}
ret := model.MethodByName(urlParts[2]).Call([]reflect.Value{})
// Return if the method has a return value
if len(ret) != 0 {
returnDAPIJSON(w, r, map[string]interface{}{
"status": "ok",
"value": fmt.Sprint(ret[0]),
}, params, "method", model.Interface())
}
}