-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_get_struct_list.go
93 lines (78 loc) · 2.23 KB
/
http_get_struct_list.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
package crudui
import (
"bytes"
"embed"
"fmt"
"log"
"net/http"
"reflect"
"text/template"
)
type structListTplObj struct {
Structs []*structListTplObjItem
URI string
}
type structListTplObjItem struct {
Name string
}
func (c *Controller) tryGetStructList(w http.ResponseWriter, r *http.Request, uri string, objFuncs ...func() interface{}) bool {
realURI := c.getRealURI(uri, r.RequestURI)
if realURI == "x/struct_list/" {
c.renderStructList(w, r, uri, objFuncs...)
return true
}
return false
}
func (c *Controller) renderStructList(w http.ResponseWriter, r *http.Request, uri string, objFuncs ...func() interface{}) {
tpl, err := c.getStructListHTML(uri, r, objFuncs...)
if err != nil {
log.Print(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error"))
return
}
w.Write([]byte(tpl))
}
func (c *Controller) getStructListHTML(uri string, r *http.Request, objFuncs ...func() interface{}) (string, error) {
structListTpl, err := embed.FS.ReadFile(htmlDir, "html/struct_list.html")
if err != nil {
return "", fmt.Errorf("error reading struct list template from embed: %w", err)
}
tplObj, err := c.getStructListTplObj(uri, r, objFuncs...)
if err != nil {
return "", fmt.Errorf("error getting struct list for html: %w", err)
}
buf := &bytes.Buffer{}
t := template.Must(template.New("structList").Parse(string(structListTpl)))
err = t.Execute(buf, &tplObj)
if err != nil {
return "", fmt.Errorf("error processing struct list template: %w", err)
}
return buf.String(), nil
}
func (c *Controller) getStructListTplObj(uri string, r *http.Request, objFuncs ...func() interface{}) (*structListTplObj, error) {
l := &structListTplObj{
URI: uri,
Structs: []*structListTplObjItem{},
}
allowedTypes := r.Context().Value(ContextValue(fmt.Sprintf("AllowedTypes_%d", OpsList)))
for _, objFunc := range objFuncs {
o := objFunc()
v := reflect.ValueOf(o)
i := reflect.Indirect(v)
s := i.Type()
if allowedTypes != nil {
v, ok := allowedTypes.(map[string]bool)[s.Name()]
if !ok || !v {
v2, ok2 := allowedTypes.(map[string]bool)["all"]
if !ok2 || !v2 {
continue
}
}
}
l.Structs = append(l.Structs, &structListTplObjItem{
Name: s.Name(),
})
}
return l, nil
}