-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_context.go
83 lines (73 loc) · 2.22 KB
/
web_context.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
package ngin
import (
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
// WebContext Web上下文
type WebContext struct {
*gin.Context
opts Options
}
func (ctx *WebContext) loadOptions(opts ...Option) {
for _, o := range opts {
o(&ctx.opts)
}
}
// RenderPage 渲染页面
func (ctx *WebContext) RenderPage(data gin.H, opts ...Option) {
ctx.loadOptions(opts...)
layout := ctx.opts.Layout
if ctx.opts.Pjax && ctx.GetHeader("X-PJAX") == "true" {
layout = ctx.opts.PjaxLayout
}
pageName := ctx.opts.PageName
tmplName := fmt.Sprintf("%s/%s_pages/%s", ctx.opts.Template, layout, pageName)
fmt.Printf("tmplName: %s\n", tmplName)
if data == nil {
data = gin.H{}
}
data[ctx.opts.SessionCurrentAccountKey] = ctx.GetCurrentAccount()
data["constant"] = ctx.opts.GlobalConstant
data["variable"] = ctx.opts.GlobalVariable
ctx.HTML(ctx.opts.StatusCode, tmplName, data)
}
// RenderSinglePage 渲染单页面
func (ctx *WebContext) RenderSinglePage(data gin.H, opts ...Option) {
ctx.loadOptions(opts...)
tmplName := fmt.Sprintf("%s/singles/%s.tmpl", ctx.opts.Template, ctx.opts.PageName)
if data == nil {
data = gin.H{}
}
data[ctx.opts.SessionCurrentAccountKey] = ctx.GetCurrentAccount()
data["constant"] = ctx.opts.GlobalConstant
data["variable"] = ctx.opts.GlobalVariable
ctx.HTML(ctx.opts.StatusCode, tmplName, data)
}
// SetCurrentAccount 设置当前账户
func (ctx *WebContext) SetCurrentAccount(data interface{}) error {
session := sessions.Default(ctx.Context)
session.Set(ctx.opts.SessionCurrentAccountKey, data)
return session.Save()
}
// GetCurrentAccount 设置当前账户
func (ctx *WebContext) GetCurrentAccount() interface{} {
session := sessions.Default(ctx.Context)
return session.Get(ctx.opts.SessionCurrentAccountKey)
}
// DelCurrentAccount 删除当前账户
func (ctx *WebContext) DelCurrentAccount() error {
session := sessions.Default(ctx.Context)
session.Delete(ctx.opts.SessionCurrentAccountKey)
return session.Save()
}
// NewWebControllerFunc Web控制器函数
func NewWebControllerFunc(ctlFunc func(ctx *WebContext), opts ...Option) gin.HandlerFunc {
return func(ctx *gin.Context) {
tmplCtx := &WebContext{
Context: ctx,
opts: newOptions(opts...),
}
ctlFunc(tmplCtx)
}
}