forked from GoAdminGroup/go-admin
/
gorilla.go
171 lines (137 loc) · 4.24 KB
/
gorilla.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
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
package gorilla
import (
"bytes"
"errors"
"github.com/chenhg5/go-admin/modules/language"
"github.com/chenhg5/go-admin/modules/logger"
"github.com/chenhg5/go-admin/modules/system"
"github.com/chenhg5/go-admin/plugins/admin/modules/constant"
template2 "html/template"
"net/http"
"regexp"
"strings"
"github.com/gorilla/mux"
"github.com/chenhg5/go-admin/context"
"github.com/chenhg5/go-admin/engine"
"github.com/chenhg5/go-admin/modules/auth"
"github.com/chenhg5/go-admin/modules/config"
"github.com/chenhg5/go-admin/modules/menu"
"github.com/chenhg5/go-admin/plugins"
"github.com/chenhg5/go-admin/template"
"github.com/chenhg5/go-admin/template/types"
)
type Gorilla struct {
}
func init() {
engine.Register(new(Gorilla))
}
func (g *Gorilla) Use(router interface{}, plugin []plugins.Plugin) error {
var (
eng *mux.Router
ok bool
)
if eng, ok = router.(*mux.Router); !ok {
return errors.New("wrong parameter")
}
reg1 := regexp.MustCompile(":(.*?)/")
reg2 := regexp.MustCompile(":(.*?)$")
for _, plug := range plugin {
var plugCopy = plug
for _, req := range plug.GetRequest() {
url := req.URL
url = reg1.ReplaceAllString(url, "{$1}/")
url = reg2.ReplaceAllString(url, "{$1}")
eng.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) {
ctx := context.NewContext(r)
params := mux.Vars(r)
for key, param := range params {
if r.URL.RawQuery == "" {
r.URL.RawQuery += strings.Replace(key, ":", "", -1) + "=" + param
} else {
r.URL.RawQuery += "&" + strings.Replace(key, ":", "", -1) + "=" + param
}
}
ctx.SetHandlers(plugCopy.GetHandler(r.URL.Path, strings.ToLower(r.Method))).Next()
for key, head := range ctx.Response.Header {
w.Header().Add(key, head[0])
}
if ctx.Response.Body == nil {
w.WriteHeader(ctx.Response.StatusCode)
return
}
w.WriteHeader(ctx.Response.StatusCode)
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(ctx.Response.Body)
_, err := w.Write(buf.Bytes())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}).Methods(strings.ToUpper(req.Method))
}
}
return nil
}
type Context struct {
Request *http.Request
Response http.ResponseWriter
}
func (g *Gorilla) Content(contextInterface interface{}, c types.GetPanel) {
var (
ctx Context
ok bool
)
if ctx, ok = contextInterface.(Context); !ok {
panic("wrong parameter")
}
globalConfig := config.Get()
sesKey, err := ctx.Request.Cookie("go_admin_session")
if err != nil || sesKey == nil {
http.Redirect(ctx.Response, ctx.Request, globalConfig.Url("/login"), http.StatusFound)
return
}
userId, ok := auth.Driver.Load(sesKey.Value)["user_id"]
if !ok {
http.Redirect(ctx.Response, ctx.Request, globalConfig.Url("/login"), http.StatusFound)
return
}
user, ok := auth.GetCurUserById(int64(userId.(float64)))
if !ok {
http.Redirect(ctx.Response, ctx.Request, globalConfig.Url("/login"), http.StatusFound)
return
}
var panel types.Panel
if !auth.CheckPermissions(user, ctx.Request.RequestURI, ctx.Request.Method) {
alert := template.Get(globalConfig.Theme).Alert().SetTitle(template2.HTML(`<i class="icon fa fa-warning"></i> ` + language.Get("error") + `!`)).
SetTheme("warning").SetContent(template2.HTML("Permission Denied")).GetContent()
panel = types.Panel{
Content: alert,
Description: "Error",
Title: "Error",
}
} else {
panel = c()
}
tmpl, tmplName := template.Get(globalConfig.Theme).GetTemplate(ctx.Request.Header.Get(constant.PjaxHeader) == "true")
ctx.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
buf := new(bytes.Buffer)
err = tmpl.ExecuteTemplate(buf, tmplName, types.Page{
User: user,
Menu: *(menu.GetGlobalMenu(user).SetActiveClass(globalConfig.UrlRemovePrefix(ctx.Request.URL.String()))),
System: types.SystemInfo{
Version: system.Version,
},
Panel: panel,
UrlPrefix: globalConfig.Prefix(),
Title: globalConfig.Title,
Logo: globalConfig.Logo,
MiniLogo: globalConfig.MiniLogo,
ColorScheme: globalConfig.ColorScheme,
IndexUrl: globalConfig.GetIndexUrl(),
})
if err != nil {
logger.Error("Gorilla Content", err)
}
ctx.Response.WriteHeader(http.StatusOK)
_, _ = ctx.Response.Write(buf.Bytes())
}